Listando todos os campos de uma tabela postgresql

25 fevereiro, 2015

Para listar todas as colunas de uma tabela no banco de dados postgreSQL, basta utilizar o seguinte comando.

SELECT *
FROM information_schema.columns
WHERE table_schema = 'your_schema'
  AND table_name   = 'your_table';

Onde:

  • your_schema é o nome do schema usado no banco de dados;
  • your_table é o nome da tabela que se deseja listar os campos

Outro modo de listagem é

SELECT attrelid::regclass, attnum, attname
FROM   pg_attribute
WHERE  attrelid = 'myschema.mytable'::regclass
AND    attnum > 0
AND    NOT attisdropped
ORDER  BY attnum;

Onde:

  • myschema.mytable é o equivalente ao esquema do banco e a tabela que se deseja listar.

Espero ter ajudado.


Número de ocorrências de uma substring em uma string

18 setembro, 2014

Quantas vezes uma string aparece dentro de outra string

Enquanto as Unit SysUtils e StrUtils contem centenas de rotinas para manipulação de strings, há sempre algo que está “faltando”,  uma função que se usa quase que diariamente, que retorne quantas vezes um string aparece dentro de outra string.

Aqui está um exemplo: no caminho “C:\Programs\MyApp\Source\Main” qual o nível da pasta “Main” – quantas vezes o carácter “\” (separador de pastas) aparece no caminho?

Uma solução seria a criação da função SubStringOccurrences:

uses StrUtils;

//case sensitive occurrence counter
function SubStringOccurences( const subString, sourceString : string) : integer;
var
pEx: integer;
begin
result := 0;
pEx := PosEx(subString, sourceString, 1);
while pEx <> 0 do
begin
Inc(result);
pEx := PosEx(subString, sourceString, pEx + Length(subString));
end;
end;

Para o caminho apresentado anteriormente, SubStringOccurrences retornará 4, isto é “\” aparece 4 vezes em  “C:\Programs\MyApp\Source\Main”.
Você precisa adicionar a Uses StrUtils para usar a função PosEx. A função PosEx retorna um valor inteiro especificando a posição da ocorrencia de uma string dentro de outra, onde nossa pesquisa começará.

Ao chamar PosEx em uma repetição do tipo while (enquanto há ocorrência) nós pegamos o número de ocorrências de uma string dentro de outra string.

Note que SubStringOccurrences e PosEx são case sensitive, diferencia maiúsculas de minúsculas. SubStringOccurrences(‘A’,’abracadabra’) retornará 0(zero), enquanto SubStringOccurrences(‘a’,’abracadabra’) retornará 5.

Uma função SubStringOccurrences sem case sensitive seria assim:

uses StrUtils;

function SubStringOccurences( const subString, sourceString : string; caseSensitive : boolean) : integer;
var
pEx: integer;
sub, source : string;
begin
if caseSensitive then
begin
sub := subString;
source := sourceString;
end
else
begin
sub := LowerCase(subString);
source := LowerCase(sourceString);
end;

result := 0;
pEx := PosEx(sub, source, 1);
while pEx <> 0 do
begin
Inc(result);
pEx := PosEx(sub, source, pEx + Length(sub));
end;
end;

Finalizando, se você precisa substituir todas as ocorrências de uma string dentro de outra string, você pode usar a função StringReplace.

 

Transcrição do site: [http://delphi.about.com/od/delphi-tips-2011/qt/number-of-occurrences-sub-string-within-string-delphi.htm]


Botão fechar na barra

30 julho, 2014

Para capturar o evento do click no botão fechar ( X ) na barra, basta fazer o seguinte procedimento:

Cria a procedure no form que deseja capturar o evento, declarado dentro da classe

procedure WMSysCommand(var MSG: TWMSysCommand); message WM_SYSCOMMAND;

e em seguida declarar a procedure da seguinte forma:

procedure TForm1.WMSYSCommand(var MSG: TWMSysCommand);
begin
if MSG.CmdType = SC_CLOSE then
begin
//aqui você faz o tratamento de fechar o form
end;
inherited;
end;

Espero ter ajudado.

Até a próxima.


Listar primeira posição vaga em tabela

17 setembro, 2013

Para saber qual a primeira posição vaga em uma tabela (mysql 5) (vaga, e não a nova), use o sql a baixo:

select g.campo+1 as proximo_codigo_vago
from tabela g
where (select f.campo from tabela f where f.campo > g.campo order by f.campo limit 1)-g.campo > 1
order by g.campo
limit 1

Explicando o SQL

select g.campo+1 as proximo_codigo_vago ( seleciona o campo atual + 1, para saber a próxima posição vaga na tabela)

from tabela g (a tabela a ser verificada)

where (select f.campo from tabela f where f.campo > g.campo order by f.campo limit 1)-g.campo > 1 (onde o próximo registro selecionado através de uma sub-sql em comparação do registro atual menos o registro atual for maior que 1, ou seja, entre próximo registro e o registro atual, existe um espaço vago)

order by g.campo (ordeno pelo campo a se busca)

limit 1 (retorno apenas o primeiro registro)

Parece meio confuso no começo, mas depois que entender a lógica fica simples de compreender.

Espero ter ajudado.

Até a próxima.


Remover Substring de uma String

22 setembro, 2011

Olá pessoal, hoje mostrarei como remover uma substring de uma string.

Para isso, usaremos a função nativa do Delphi chamada Delete, para isso é preciso declarar a unit System.

Mas para ficar melhor, criaremos uma procedure para melhor entendermos.

Então vamos lá.

procedure RemovePalavra(var origem: string; apagar: string);

var

InicioPalavra, TamanhoPalavra : Integer;

begin

InicioPalavra := pos(apagar,origem);

TamanhoPalavra := length(apagar);

if InicioPalavra > 0 then

Delete(origem,InicioPalavra,TamanhoPalavra);

end;

A função Delete recebe como parâmetro :

  • String que contem a palavra a ser removida;
  • Posição inicial onde achou a palavra a ser removida;
  • Tamanho da palavra a ser removida.

Obs.: Vale lembrar que existe diferença entre maiúscula e minúscula, ou seja é Case Sensitive.

Obrigado.

Espero ter ajudado.

Até a próxima.


Repetir expressão várias vezes em Delphi

19 setembro, 2011

Olá, neste post irei mostrar uma função para repetir uma expressão várias vezes.

A função em si se chama DupeString, deve-se declarar a uses StrUtils.

Para usa-la, devemos passar como parâmetro a expressão a ser repetida e a quantidade de vezes que queremos repetir essa expressão.

Vamos ao exemplo:

….

var

palavra : string;

begin

palavra := DupeString(‘Ha’,5);

ShowMessage(palavra);

end;

O resultado obtido será a expressão ‘Ha’ repetida 5 vezes, ‘HaHaHaHaHa’.

Espero ter ajudado, até a próxima.


Cast com datas no MySQL

25 agosto, 2011

Uma dica para fazer comparação entre datas sem necessidade de hora, basta usar o cast, ou seja, forçar um datetime se transformar em apenas data.
Um exemplo seria pegar todos os registros de um log em um determinado dia, independente da hora do registro.
Então vamos a prática.

Select usuario,descricao,data from log_acao where cast(data as date) = cast(data_parametro as date)

ou

Select usuario,descricao,data from log_acao where date(data) = date(data_parametro)

Espero ter ajudado. Até a próxima.


Dicas para report builder em delphi

20 junho, 2011

Olá, postarei o link do site oficial de dicas do próprio report builder.
Para quem esta começando e para quem já usa essa excelente ferramenta de gerar relatórios.
www.digital-metaphors.com:8080
Espero ter ajudado.


Trabalhando com Datas no Delphi

18 maio, 2011

Olá, estou meio atarefado e não estou com tempo para postar mais coisas.

Bom, irei postar algumas rotinas para trabalhar com datas no delphi 5, usando algumas rotinas existentes no Delphi 2010.

Sei que não são todas as rotinas, mas é de grande ajuda.

unit Datas;

interface

uses
SysUtils, Math;

resourcestring
SInvalidDateTime = ””’%s”” is not a valid date and time’;

function DaysBetween(const ANow, AThen: TDateTime): Integer;
function DaySpan(const ANow, AThen: TDateTime): Double;
function SpanOfNowAndThen(const ANow, AThen: TDateTime): TDateTime;
function DayOf(const AValue: TDateTime): Word;
function MonthOfTheYear(const AValue: TDateTime): Word;
function MonthOf(const AValue: TDateTime): Word;
function YearOf(const AValue: TDateTime): Word;
function CurrentYear: Word;
function DiasUteis(mes,ano:Integer ):integer;

function Today: TDateTime;
function Yesterday: TDateTime;
function Tomorrow: TDateTime;
function DaysInMonth(const AValue: TDateTime): Word;
function DaysInAMonth(const AYear, AMonth: Word): Word;

function RecodeTime(const AValue: TDateTime; const AHour, AMinute, ASecond,
AMilliSecond: Word): TDateTime;
function RecodeDateTime(const AValue: TDateTime; const AYear, AMonth, ADay,
AHour, AMinute, ASecond, AMilliSecond: Word): TDateTime;
function TryRecodeDateTime(const AValue: TDateTime; const AYear, AMonth, ADay,
AHour, AMinute, ASecond, AMilliSecond: Word; out AResult: TDateTime): Boolean;

function StartOfTheMonth(const AValue: TDateTime): TDateTime;
function EndOfTheMonth(const AValue: TDateTime): TDateTime;
function EndOfTheDay(const AValue: TDateTime): TDateTime;
function DayOfTheWeek(const AValue: TDateTime): Word;

function IncYear(const Anow: TDateTime; Anos : integer): TDateTime;
function IncMonth(const DateTime: TDateTime; NumberOfMonths: Integer): TDateTime;

procedure InvalidDateTimeError(const AYear, AMonth, ADay, AHour, AMinute,
ASecond, AMilliSecond: Word; const ABaseDate: TDateTime);

procedure DecodeDateTime(const AValue: TDateTime; out AYear, AMonth, ADay,
AHour, AMinute, ASecond, AMilliSecond: Word);

function TryEncodeDateTime(const AYear, AMonth, ADay, AHour, AMinute, ASecond,
AMilliSecond: Word; out AValue: TDateTime): Boolean;

const
RecodeLeaveFieldAsIs = High(Word);
HoursPerDay   = 24;
MinsPerHour   = 60;
SecsPerMin    = 60;
MSecsPerSec   = 1000;
MinsPerDay    = HoursPerDay * MinsPerHour;
SecsPerDay    = MinsPerDay * SecsPerMin;
SecsPerHour   = SecsPerMin * MinsPerHour;
MSecsPerDay   = SecsPerDay * MSecsPerSec;

implementation

function TryEncodeTime(Hour, Min, Sec, MSec: Word; out Time: TDateTime): Boolean;
var
TS: TTimeStamp;
begin
Result := False;
if (Hour < HoursPerDay) and (Min < MinsPerHour) and (Sec < SecsPerMin) and (MSec < MSecsPerSec) then
begin
TS.Time :=  (Hour * (MinsPerHour * SecsPerMin * MSecsPerSec))
+ (Min * SecsPerMin * MSecsPerSec)
+ (Sec * MSecsPerSec)
+  MSec;
TS.Date := DateDelta; // This is the “zero” day for a TTimeStamp, days between 1/1/0001 and 12/30/1899 including the latter date
Time := TimeStampToDateTime(TS);
Result := True;
end;
end;

function TryEncodeDate(Year, Month, Day: Word; out Date: TDateTime): Boolean;
var
I: Integer;
DayTable: PDayTable;
begin
Result := False;
DayTable := @MonthDays[IsLeapYear(Year)];
if (Year >= 1) and (Year <= 9999) and (Month >= 1) and (Month <= 12) and
(Day >= 1) and (Day <= DayTable^[Month]) then
begin
for I := 1 to Month – 1 do Inc(Day, DayTable^[I]);
I := Year – 1;
Date := I * 365 + I div 4 – I div 100 + I div 400 + Day – DateDelta;
Result := True;
end;
end;

function TryEncodeDateTime(const AYear, AMonth, ADay, AHour, AMinute, ASecond,
AMilliSecond: Word; out AValue: TDateTime): Boolean;
var
LTime: TDateTime;
begin
Result := TryEncodeDate(AYear, AMonth, ADay, AValue);
if Result then
begin
Result := TryEncodeTime(AHour, AMinute, ASecond, AMilliSecond, LTime);
if Result then
if AValue >= 0 then
AValue := AValue + LTime
else
AValue := AValue – LTime
end;
end;

procedure DecodeDateTime(const AValue: TDateTime; out AYear, AMonth, ADay,
AHour, AMinute, ASecond, AMilliSecond: Word);
begin
DecodeDate(AValue, AYear, AMonth, ADay);
DecodeTime(AValue, AHour, AMinute, ASecond, AMilliSecond);
end;

procedure IncAMonth(var Year, Month, Day: Word; NumberOfMonths: Integer = 1);
var
DayTable: PDayTable;
Sign: Integer;
begin
if NumberOfMonths >= 0 then Sign := 1 else Sign := -1;
Year := Year + (NumberOfMonths div 12);
NumberOfMonths := NumberOfMonths mod 12;
Inc(Month, NumberOfMonths);
if Word(Month-1) > 11 then    // if Month <= 0, word(Month-1) > 11)
begin
Inc(Year, Sign);
Inc(Month, -12 * Sign);
end;
DayTable := @MonthDays[IsLeapYear(Year)];
if Day > DayTable^[Month] then Day := DayTable^[Month];
end;

function IncMonth(const DateTime: TDateTime; NumberOfMonths: Integer): TDateTime;
var
Year, Month, Day: Word;
begin
DecodeDate(DateTime, Year, Month, Day);
IncAMonth(Year, Month, Day, NumberOfMonths);
Result := EncodeDate(Year, Month, Day);
ReplaceTime(Result, DateTime);
end;

function DaysInMonth(const AValue: TDateTime): Word;
var
LYear, LMonth, LDay: Word;
begin
DecodeDate(AValue, LYear, LMonth, LDay);
Result := DaysInAMonth(LYear, LMonth);
end;

function DaysInAMonth(const AYear, AMonth: Word): Word;
begin
Result := MonthDays[(AMonth = 2) and IsLeapYear(AYear), AMonth];
end;

function StartOfTheMonth(const AValue: TDateTime): TDateTime;
var
LYear, LMonth, LDay: Word;
begin
DecodeDate(AValue, LYear, LMonth, LDay);
Result := EncodeDate(LYear, LMonth, 1);
end;

function EndOfTheMonth(const AValue: TDateTime): TDateTime;
var
LYear, LMonth, LDay: Word;
begin
DecodeDate(AValue, LYear, LMonth, LDay);
Result := EndOfTheDay(EncodeDate(LYear, LMonth, DaysInAMonth(LYear, LMonth)));
end;

function StartOfTheWeek(const AValue: TDateTime): TDateTime;
begin
Result := Trunc(AValue) – (DayOfTheWeek(AValue) – 1);
end;

function EndOfTheWeek(const AValue: TDateTime): TDateTime;
begin
Result := EndOfTheDay(StartOfTheWeek(AValue) + 6);
end;

function StartOfTheDay(const AValue: TDateTime): TDateTime;
begin
Result := Trunc(AValue);
end;

function DayOfTheWeek(const AValue: TDateTime): Word;
begin
Result := (DateTimeToTimeStamp(AValue).Date – 1) mod 7 + 1;
end;

function EndOfTheDay(const AValue: TDateTime): TDateTime;
begin
Result := RecodeTime(AValue, 23, 59, 59, 999);
end;

function RecodeTime(const AValue: TDateTime; const AHour, AMinute, ASecond,
AMilliSecond: Word): TDateTime;
begin
Result := RecodeDateTime(AValue, RecodeLeaveFieldAsIs, RecodeLeaveFieldAsIs,
RecodeLeaveFieldAsIs, AHour, AMinute, ASecond, AMilliSecond);
end;

function RecodeDateTime(const AValue: TDateTime; const AYear, AMonth, ADay,
AHour, AMinute, ASecond, AMilliSecond: Word): TDateTime;
begin
if not TryRecodeDateTime(AValue, AYear, AMonth, ADay,
AHour, AMinute, ASecond, AMilliSecond, Result) then
InvalidDateTimeError(AYear, AMonth, ADay,
AHour, AMinute, ASecond, AMilliSecond,
AValue);
end;

procedure InvalidDateTimeError(const AYear, AMonth, ADay, AHour, AMinute,
ASecond, AMilliSecond: Word; const ABaseDate: TDateTime);
function Translate(AOrig, AValue: Word): string;
begin
if AValue = RecodeLeaveFieldAsIs then
if ABaseDate = 0 then
Result := ‘?’
else
Result := IntToStr(AOrig)
else
Result := IntToStr(AValue);
end;
var
LYear, LMonth, LDay, LHour, LMinute, LSecond, LMilliSecond: Word;
begin
DecodeDate(ABaseDate, LYear, LMonth, LDay);
DecodeTime(ABaseDate, LHour, LMinute, LSecond, LMilliSecond);
raise EConvertError.CreateFmt(SInvalidDateTime,
[Translate(LYear, AYear) + ‘-‘ +
Translate(LMonth, AMonth) + ‘-‘ +
Translate(LDay, ADay) + ‘ ‘ +
Translate(LHour, AHour) + ‘:’ +
Translate(LMinute, AMinute) + ‘:’ +
Translate(LSecond, ASecond) + ‘.’ +
Translate(LMilliSecond, AMilliSecond)]);
end;

function TryRecodeDateTime(const AValue: TDateTime; const AYear, AMonth, ADay,
AHour, AMinute, ASecond, AMilliSecond: Word; out AResult: TDateTime): Boolean;
var
LYear, LMonth, LDay, LHour, LMinute, LSecond, LMilliSecond: Word;
begin
DecodeDateTime(AValue, LYear, LMonth, LDay,
LHour, LMinute, LSecond, LMilliSecond);
if AYear <> RecodeLeaveFieldAsIs then LYear := AYear;
if AMonth <> RecodeLeaveFieldAsIs then LMonth := AMonth;
if ADay <> RecodeLeaveFieldAsIs then LDay := ADay;
if AHour <> RecodeLeaveFieldAsIs then LHour := AHour;
if AMinute <> RecodeLeaveFieldAsIs then LMinute := AMinute;
if ASecond <> RecodeLeaveFieldAsIs then LSecond := ASecond;
if AMilliSecond <> RecodeLeaveFieldAsIs then LMilliSecond := AMilliSecond;
Result := TryEncodeDateTime(LYear, LMonth, LDay,
LHour, LMinute, LSecond, LMilliSecond, AResult);
end;

function DaysBetween(const ANow, AThen: TDateTime): Integer;
begin
Result := Trunc(DaySpan(ANow, AThen));
end;

function DaySpan(const ANow, AThen: TDateTime): Double;
begin
Result := SpanOfNowAndThen(ANow, AThen);
end;

function SpanOfNowAndThen(const ANow, AThen: TDateTime): TDateTime;
begin
if ANow < AThen then
Result := AThen – ANow
else
Result := ANow – AThen;
end;

function DayOf(const AValue: TDateTime): Word;
var
LYear, LMonth: Word;
begin
DecodeDate(AValue, LYear, LMonth, Result);
end;

function MonthOfTheYear(const AValue: TDateTime): Word;
begin
Result := MonthOf(AValue);
end;

function MonthOf(const AValue: TDateTime): Word;
var
LYear, LDay: Word;
begin
DecodeDate(AValue, LYear, Result, LDay);
end;

function YearOf(const AValue: TDateTime): Word;
var
LMonth, LDay: Word;
begin
DecodeDate(AValue, Result, LMonth, LDay);
end;

function CurrentYear: Word;
var
LMonth, LDay: Word;
begin
DecodeDate(Date, Result, LMonth, LDay);
end;

function Today: TDateTime;
begin
Result := Date;
end;

function Yesterday: TDateTime;
begin
Result := Date – 1;
end;

function Tomorrow: TDateTime;
begin
Result := Date + 1;
end;

function IncYear(const Anow: TDateTime; Anos : integer): TDateTime;
var
LMonth, LDay, LYear: Word;
begin
DecodeDate(ANow, LYear, LMonth, LDay);
lYear:=LYear+Anos;
Result:=EncodeDate(LYear, LMonth, LDay);
end;

function DiasUteis(mes,ano:Integer ):integer; // Dias Uteis de Um Mês Especifico
var
data : TDateTime;
contador : Integer;
begin
data := StrToDate(’01/’+IntTOStr(mes)+’/’+IntToStr(ano));
Contador := 0;
while (MonthOf(data)= mes) do
begin
if ( DayOfWeek(data) in [2,3,4,5,6] ) then
Inc(Contador);
Data := Data + 1
end;
result := contador;
end;

end.

Espero ter ajudado.

Até a próxima.

Agradecimento a Márcio Torres pela função de contar os dias Ulteis no Mês.


Adicionar dados a Área de Transferência através do Delphi

1 setembro, 2010

Olá pessoal, postarei um simples exemplo de como copiar o conteudo de um edit e jogá-lo para a Área de Transferência.

Para isso, devemos declarar no uses a unit ClipBrd.

Vamos ao exemplo:

Colocando o conteúdo de um edit na Área de Transferência

Clipboard.asText := Edit1.Text;

Colocando o conteúdo da Área de Transferência em um edit

edit1.Text := Clipboar.asText;

obs.:  antes de colocar o conteúdo da Área de Transferência em um edit, verifique se o conteúdo é um texto, para isso use:

if Clipboard.HasFormat(CF_TEXT) then

isto irá verificar se o conteúdo da Área de Transferência é um texto.

Espero ter ajudado, até a próxima.