SQL错误:在使用现有数据插入新数据时无法插入重复ID

时间:2012-07-11 16:00:09

标签: sql sql-server-2008

我的修改页面上有一个文本框,用于保存数据库中的现有数据。此数据是SQL Server表中的单独行,但显示为文本框中以逗号分隔的单行。

例如:table

keyid   name 
--------------
  101     ss
  105     hh
  109     tt

在我的网络表单中,它显示在ss,hh,tt之类的文本框中。有一个桥牌表(Keysproducts),其中包含keyidproductid(与keyid相关的产品)

我的问题是:

在我的文本框中添加更多条目以及现有条目时,我收到此错误消息,指出未插入重复值并显示我现有的ID。下面是我的存储过程。

我正在检查keyname是否存在,如果不是我插入行,否则我会更新它。如果我的方法有误,请指导我。

create PROCEDURE [dbo].[modify] 
      (
        @keyName nvarchar(256),
        @productdbid uniqueidentifier

      )
AS
Begin
  declare 
    @productid uniqueidentifier,
    @keyid uniqueidentifier,
    @id uniqueidentifier;

    declare @keydata table (keyid uniqueidentifier);

    set @productid =(select ProductID from Products where ProductID = @productdbid );

Begin


    if not exists(select keyname from keys where KeyName = @keyName)
    begin
       insert into Keys(KeyId, KeyName)
       output inserted.KeyId into @keydata(keyid)
       values (newid(), @keyName);

       select @keyid = keyid from @keydata;

       insert into KeysProducts(KeyId,productId)
        values (@keyid, @productid);
     end
     else
     begin
        set @id = (select keyid  from keys where KeyName = @keyName)

        update keywords 
        set KeyId = @id, KeyName = @keyName 
        where KeyName= @keyName;
    end

    if not exists(select * from Keysproducts where ProductID = @productid and KeyId= @id) 
     begin
        insert into Keysproducts(KeyId, ProductID)
        values (@id, @productid);       
     end
     else
     begin
         update Keysproducts 
         set KeyId = @id, productID = @productid;
     end
  end
end

1 个答案:

答案 0 :(得分:0)

好吧,我想我们需要更多关于你如何使用这个存储过程的信息。如果您的文本框最初有ss,hh,tt,并且我将其更改为ss,hh,tt,zz,例如,我假设您仍然为每个值运行一次程序?所以你为ss运行它,然后再单独运行hh,tt和zz?

从哪里获取productdbid参数值?

你对桌子有什么限制,哪一个被违反(PK或一些独特的约束)?

你得到了什么确切的错误?

我还想指出您上次更新时没有WHERE子句,因此您尝试更新表中的每条记录。如果这个Keysproduct表是你得到错误的那个,这就是原因。

 begin          
    update Keysproducts   
    set KeyId = @id, productID = @productid;
 end 
相关问题