function TFRMSOEDIT.vartosql(value: Variant): wideString;
var
tmp: widestring;
begin
if (varisnull(value)) or (varisempty(value)) then
Result := 'NULL'
else
case Vartype(value) of
varDate:
begin
tmp := formatDatetime('yyyy-mm-dd hh:mm:ss', VartoDatetime(value));
Result := Quotedstr(tmp);
end;
varString, varOlestr:
Result := Quotedstr(Trim(Vartostr(value)));
varboolean:
begin
if value then
Result := '1'
else
Result := '0';
end;
varSmallint, varInteger, varDouble, varShortInt, varInt64, varLongWord, varCurrency:
begin
Result := trim(Vartostr(value));
end;
else
Result := Quotedstr(Trim(Vartostr(value)));
end;
end;
//TableName 表名
//keys 字段名,支持多个主键
procedure TFRMSOEDIT.Sql2ApplyUpdates(cds1: THxDataSet; TableName, keys: WideString);
var
i, j: integer;
s1, s2, CmdStr, keyWhere: string;
cds: THxDataSet;
keyList, sqlStr: TStringList;
begin
try
sqlStr := TStringList.Create;
cds := THxDataSet.Create(nil);
cds.Data := cds1.Delta;
//获取每个Key的值
keyList := split(keys, ',');
keyWhere := ' Where ';
for j := 0 to keyList.count - 1 do
begin
if j = (keyList.count - 1) then
begin
keyWhere := keyWhere + keyList[j] + ' = ' + VarToSql(cds[keyList[j]]);
end
else
begin
keyWhere := keyWhere + keyList[j] + ' = ' + VarToSql(cds[keyList[j]]) + ' and ';
end;
end;
if cds.RecordCount > 0 then
begin
cds.First;
while not cds.Eof do
begin
CmdStr := '';
if cds.UpdateStatus = usModified then
begin
s1 := '';
for i := 0 to cds.FieldCount - 1 do
begin
if cds.Fields[i].NewValue <> Variants.Unassigned then
begin
if s1 = '' then
s1 := Trim(cds.Fields[i].FieldName) + ' = ' + VarToSql(cds.Fields[i].Value)
else
s1 := s1 + ',' + Trim(cds.Fields[i].FieldName) + ' = ' + VarToSql(cds.Fields[i].Value);
end;
end;
if s1 <> '' then
begin
CmdStr := 'Update ' + TableName + ' Set ' + s1 + keyWhere;
end;
end
else if cds.UpdateStatus = usInserted then
begin
s1 := '';
for i := 0 to cds.FieldCount - 1 do
begin
if (cds.Fields[i].NewValue <> Variants.Unassigned) and (cds.Fields[i].NewValue <> '') then
begin
if s1 = '' then
begin
s1 := Trim(cds.Fields[i].FieldName);
s2 := VarToSql(cds.Fields[i].Value);
end
else
begin
s1 := s1 + ',' + Trim(cds.Fields[i].FieldName);
s2 := s2 + ',' + VarToSql(cds.Fields[i].Value);
end;
end;
end;
if s1 <> '' then
begin
CmdStr := 'Insert into ' + TableName + '(' + s1 + ') Values (' + s2 + ')';
end;
end
else if cds.UpdateStatus = usDeleted then
begin
CmdStr := 'Delete ' + TableName + keyWhere;
end;
if CmdStr <> '' then
begin
sqlStr.Add(CmdStr);
end;
cds.Next;
end;
end;
ExcuteSql(CmdStr);
finally
sqlStr.Free;
cds.Free;
end;
end;
procedure TFRMSOEDIT.Cds2SqlExec;
begin
Sql2ApplyUpdates(QyDtl,'quotedtl','fid01');
end;
function TFRMSOEDIT.split(s,s1:string):TStringList;
begin
Result:=TStringList.Create;
while Pos(s1,s)>0 do
begin
Result.Add(Copy(s,1,Pos(s1,s)-1));
Delete(s,1,Pos(s1,s));
end;
Result.Add(s);
end;
来源:博客园
作者:zyb2016
链接:https://www.cnblogs.com/zyb2016/p/11592393.html