不是每个时候每一种情况下都是“使用存储过程更快”,存储过程的快速在于其可以对批处理命令进行预编译,从而使得批量的命令执行更加有效率,这个主要体现在计算过程,而对于简单的insert和select则不尽如此了。对于mssqlserver,可以使用批量的insert:
var
Insert_Lst: TstringList;
begin
Insert_Lst := TStringList.Create;
try
for I := 0 to Count - 1 do //最好每500~1000条做一批
Insert_lst.Add('Insert into tablename (Field1,Field2...) Value(''+StringValue1+''','+IntValue ...')');
Insert_Lst.LineBrek := ';';//对于低版本如果不支持LineBreak的可以在上面的行末尾增加一个分号来解决
ADOCommand.CommandText := Insert_Lst.Text;
ADOCommand.Execute;
finally
Insert_Lst.Free;
end;
end;
一个以前写的示例:
const AnsiString SplitEmpty="",Split=";";
DWORD StartTime=GetTickCount();
int Count,iCacheSize=1000;
TStringList *CacheList=new TStringList();
try
{
for(int i=0;i<200000;i++)
{
if(Count)
CacheList->Add(";Insert into tablename (field1,field2,field3[...,fieldn]) values(value1,value2,value3[...,valuen])");
else
CacheList->Add("Insert into tablename (field1,field2,field3[...,fieldn]) values(value1,value2,value3[...,valuen])");
Count++;
if(Count==iCacheSize)
{
ADOCommand->CommandText=CacheList->Text;
CacheList->Clear();
Count=0;
ADOCommand->Execute();
}
}
if(Count>0)
{
ADOCommand->CommandText=CacheList->Text;
ADOCommand->Execute();
}
}
__finally
{
CacheList->Free();
}
DWORD EndTime=GetTickCount();
ShowMessage((int)(EndTime-StartTime));
附注:此方法不适用于ACCESS数据库!