



Função para quem precisa converter quaisquer valores para serem aceitos em instruções Sql.
Ela pode ser totalmente configurada através dos parâmetros, de acordo com as exigências do seu
SGDB preferido.
Foi feita no Delphi XE7, mas pode ser facilmente adaptada para versões anteriores.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | interface uses System.SysUtils, System.StrUtils, System.Variants; function VarToSql(const pValue: Variant; pTrimToNull: Boolean = True; pDateTimeFormat: string = 'dd.mm.yyyy hh:nn:ss:zzz'; pQuoteDate: Boolean = True; pQuoteDateChar: Char = ''''; pNullString: string = 'NULL'): string; implementation function VarToSql(const pValue: Variant; pTrimToNull: Boolean; pDateTimeFormat: string; pQuoteDate: Boolean; pQuoteDateChar: Char; pNullString: string): string; var FDecimalSeparatorOld: Char; FValue : Variant; begin FValue := pValue; if pNullString.Trim.IsEmpty then pNullString := 'NULL'; case AnsiIndexText(VarTypeAsText(VarType(FValue)), ['FMTBcdVariantType']) of 0: FValue := VarAsType(FValue, varDouble); // poderão ser adicionados mais tipos específicos end; // varSingle, varDouble, varCurrency if VarIsFloat(FValue) then with FormatSettings do begin FDecimalSeparatorOld := DecimalSeparator; DecimalSeparator := '.'; Result := FloatToStr(FValue, FormatSettings); DecimalSeparator := FDecimalSeparatorOld; end; {varSmallInt, varInteger, varBoolean, varShortInt, varByte, varWord, varLongWord, varInt64, varUInt64} if VarIsOrdinal(FValue) then Result := VarToStr(FValue); // varOleStr, varString, varUString if VarIsStr(FValue) then Result := QuotedStr(FValue); // varDate if VarIsType(FValue, varDate) then Result := IfThen(pQuoteDate, AnsiQuotedStr(FormatDateTime(pDateTimeFormat, VarToDateTime(FValue)), pQuoteDateChar), FormatDateTime(pDateTimeFormat, VarToDateTime(FValue))); if ((VarIsClear(FValue)) or (VarIsNull(FValue)) or (VarIsEmpty(FValue)) or (VarIsError(FValue))) then Result := pNullString; if pTrimToNull then if (Result.Trim.IsEmpty) or (Result.DeQuotedString.Trim.IsEmpty) then Result := pNullString; end; |
Algumas formas de utilização:
1 2 3 | Sql := VarToSql(DateEdit.Date); Sql := VarToSql(DataSet.FieldByName('valor').AsCurrency); Sql := VarToSql(FNome); |