动态 SQL: 插入 id 不是自动增量

Dynamic SQL: insert id not autoincrement

我想将一些行从 table 复制到同一个 table。 TForms table 的 id 列不是自动递增的,而是它的 primary key。我怎样才能做到这一点?

set @sourcetid = 17
set @newtbn = 15
set @template ='
INSERT INTO ' +@DB + '.[Tforms]
           (id
           ,[tablename])

     select id,
            @newtbn)
     from '+ @DB+ '.[Tforms] where tid=' +str(@sourcetid) 
exec sp_Executesql @template

一种方法是获取最大 ID 并将其添加到每个当前 ID:

insert into ' +@DB + '.[Tforms](id, [tablename])
     select (max_id + id) as id, @newtbn
     from (select t.*, max(id) over () as max_id
           from '+ @DB+ '.[Tforms] t
          ) t
     where tid = ' +str(@sourcetid) ;

备注:

  • 如果当前id可以为零,则添加1。如果 ids 可以为负数,则不能使用此方法。
  • 您应该将主键设为 identitynewid(),这样您就不必手动设置它。
  • 如果多次重复此操作,在某些情况下可能会溢出。
  • 不要将比较作为字符串传递。相反,使用参数(通过 sp_executesql)。

编辑:

无论最小值和最大值如何,更通用的方法都有效:

insert into ' +@DB + '.[Tforms](id, [tablename])
     select max_id + row_number() over (order by id) as id, @newtbn
     from (select t.*, max(id) over () as max_id
           from '+ @DB+ '.[Tforms] t
          ) t
     where tid = ' +str(@sourcetid) ;