在我们编写软件时,经常会有这样的情况:将一个数据集的某些字段赋给别外一个数据的对应字段
通常的写法是:
destDataSet.FieldByName('FieldA').Value := srcDataSet.FieldByName('SrcFieldA').Value;
destDataSet.FieldByName('FieldB').Value := srcDataSet.FieldByName('SrcFieldB').Value;
destDataSet.FieldByName('FieldC').Value := srcDataSet.FieldByName('SrcFieldC').Value;
destDataSet.FieldByName('FieldD').Value := srcDataSet.FieldByName('SrcFieldD').Value;
destDataSet.FieldByName('FieldE').Value := srcDataSet.FieldByName('SrcFieldE').Value;
destDataSet.FieldByName('FieldF').Value := srcDataSet.FieldByName('SrcFieldF').Value;
destDataSet.FieldByName('FieldG').Value := srcDataSet.FieldByName('SrcFieldG').Value;
.........
冗长的代码,编写时不停的COPY、Paste,写的累,看的人也累,维护的时候面对一堆的代码甚至有头晕晕的感觉。
有没想过,上面的代码,其本质都是相同的:将一个数据集的某些字段赋给别外一个数据的对应字段。根据其本质,我们就可以写出一个通用的赋值函数出来,将它放到自身的函数库中,供所有项目使用:
{ 将数据集的指定字段值赋给对应的目标数据集字段
srcStr: 源数据集字段名 多字段间用";"隔开
destStr: 接受值数据集字段名 多字段间用";"隔开
sChkField: 参照字段,用于IsOnlyEmpty参数为真时 多字段间用";"隔开
IsOnlyEmpty: 如果字段存在于sChkField中,且该字段不为空,则不赋值 }
Procedure CopyFiledsValue(srcStr,destStr: String; srcDst,destDst: TDataSet;
sChkField: string=''; IsOnlyEmpty: Boolean=False);
var sSrcStr,sDestStr, sChkFields: TStrings;
I: Integer;
begin
sSrcStr := TStringList.Create;
sDestStr := TStringList.Create;
sChkFields := TStringList.Create;
Try
if DestStr = '' then DestStr := SrcStr;
DecompostStr(srcStr,sSrcStr);
DecompostStr(destStr,sDestStr);
DecompostStr(sChkField,sChkFields);
for I := 0 to sSrcStr.Count - 1 do
begin
if (srcDst.FindField(sSrcStr[I])=nil) or (destDst.FindField(sDestStr[I])=nil) then Continue;
if IsOnlyEmpty and (sChkFields.IndexOf(sDestStr[I]) >= 0)
and not (srcDst.FindField(sSrcStr[I]).IsNull or (srcDst.FindField(sSrcStr[I]).AsString = '')) then Continue;
if not (destDst.State in [dsEdit,dsInsert]) then destDst.Edit;
destDst.FindField(sDestStr[I]).AsString := srcDst.FindField(sSrcStr[I]).AsString;
end;
Finally
sSrcStr.Free;
sDestStr.Free;
sChkFields.Free;
End;
end;
相关函数:
//将字符串转换为字符列表 各项目间用";"分隔开
procedure DecompostStr(str: WideString; rstStrs: TStrings);
var I: Integer;
subStr: string;
begin
while Trim(str) <> '' do
begin
I := Pos(';',str);
if I <=0 then
begin
subStr := str;
str := '';
end else
begin
subStr := copy(str, 1, I-1);
str := copy(str, I+1,Length(str)-I);
end;
rstStrs.Add(subStr);
end;
end;
简单调用试例如下,即可完成多字段间一次性赋值:
CopyFiledsValue('Card_No;Reg_No;Sick_Nm;Sex;Age','',pub_activesick_cds,cds_mst);
或
CopyFiledsValue('Doctor_Nm;Dgn_Date;Sick_Nm;Sex;Age',
'Dgn_Dct_Nm;Dgn_Date;Sick_Nm;Sex;Age',tmpCds,cds_mst);
当有多字段间需要赋值时,是不是很简单? ^_^
作者:九天 Email: NineSkySoft@126.com
我的个人网站: http://www.nineskysoft.com