delphi ----处理SQL server主键自增,并给定值

获取一个表中最大的值。

function GetNEWID(tablename: string): string;
begin
  Result:='';
  with DMW_Public.DQ_Pub do
  begin
    Close;
    SQL.Clear;
    SQL.Add('SELECT IDENT_CURRENT('''+tablename+''') + IDENT_INCR('''+tablename+''') as newid');
    Open;
    if(Fieldbyname('newid').AsString='') then result:='0'
    else
      Result:=Fieldbyname('newid').AsString;
  end;
end;

//IDENT_CURRENT( 'tablename' ) 返回为指定的表或视图生成的最后一个标识值。所生成的最后一个标识值可以针对任何会话和任何作用域。

IDENT_INCR ( 'tablename' ) 返回增量值(返回形式为 numeric (@@MAXPRECISION,0)),该值是在带有标识列的表或视图中创建标识列时指定的。

SID:= GetNEWID('表名');//取ID

tbSql.add('set identity_insert  表名 on ');

然后进行正常插入数据操作。

sInsertMain:=' insert into raw_mains(id,.....)  '
      +' values ('''+SID+''',)   ';
tbSql.add(sInsertMain);

tbSql.add('set identity_insert  表名 off');

原文地址:https://www.cnblogs.com/michellexiaoqi/p/8031448.html