增加现有的db列

时间:2013-05-01 04:48:04

标签: sql-server-2005 insert auto-increment identity

我正在尝试制作表格的精确副本,但更改了2列的值。基本上我在db表中有800个条目,需要800个以上,但我需要其中一个列的值(Set_id为11),我需要另一个的值来自动递增...但不幸的是,列不是标识插入。我创建了一个临时表并将现有表复制到临时表中。然后我尝试将临时表写回原始表,将该列作为11并尝试使doctype id列以860开始,然后每个条目自动增加1。我创建了这个游标:

declare @id int, @document char(30)
select @id = 860
declare documents cursor for
/* This will select all Non-Physician users */
  select tag from cabinet..document_names

open documents

fetch next from documents into @document
while @@fetch_status <> -1
begin
 select @id = @id +1
      if not exists (select * from cabinet..document_names where set_id='11' and tag=@document)
      insert into cabinet..document_names (TAG, TAGORDER, ACTIVE,QUEUE, REASON, FORM,DIRECT_VIEW,GLOBAL,FU_SIGN,SIGN_X,
SIGN_Y,SIGN_W,SIGN_H,ANNOTATE,doctype_id,CODE,CALCTABLE_ID, DOC_TYPE,SET_ID,SUSPEND_DELAY,Text_Editing,Restrict_Viewing,Viewing_Expire,
Viewing_Period , DocHdrLength,DocHdrSearchString,DocFtrLength,DocFtrPageNo,DocRuleId,Outbound,SigQueue,SigReason)
select TAG, TAGORDER, ACTIVE,QUEUE, REASON, FORM,DIRECT_VIEW,GLOBAL,FU_SIGN,SIGN_X,
SIGN_Y,SIGN_W,SIGN_H,ANNOTATE,@ID,CODE,CALCTABLE_ID, DOC_TYPE,'11',SUSPEND_DELAY,Text_Editing,Restrict_Viewing,Viewing_Expire,
Viewing_Period , DocHdrLength,DocHdrSearchString,DocFtrLength,DocFtrPageNo,DocRuleId,Outbound,SigQueue,SigReason from
cabinet..document_names_temp 


fetch next from documents into @document

end
close documents 
deallocate documents

它正在做我想要的,除了doctype id重复自己为861,861等等。我需要在每次进入原始表后将该数字增加1。任何有关我搞砸的地方的帮助都是适当的!谢谢!

1 个答案:

答案 0 :(得分:1)

应该不是

  INSERT INTO cabinet..document_names ([columns])
  SELECT [columns] 
  FROM cabinet..document_names_temp 

还有一个WHERE声明?

之类的东西
  INSERT INTO cabinet..document_names ([columns])
  SELECT [columns] 
  FROM cabinet..document_names_temp 
  WHERE TAG = @Document

目前,您的插入只会插入document_names_temp中可以找到的doctype_id设置为@ID的每条记录,这可以解释861,861,861的重复...您可能拥有相同的内容docttype_id 862的记录数量。