0

我在文本框中输入关键字,例如 test、check、..etc。我将这些关键字作为单独的行插入到我的数据库中以检查它是否存在,如果存在则更新或插入它。这个关键字 ID 和代表这个的项目id 应插入到桥表中。插入现有关键字时会引发错误:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

Cannot insert the value NULL into column 'KeywordId', table 'dbo.Keywordsitems'; column does not allow nulls. INSERT fails.

我正在使用以下存储过程

ALTER PROCEDURE [dbo].[InsertKeywords] 
(
  @keywordName nvarchar(256),
  @itemid uniqueidentifier
)
AS
begin
  declare 
    @itemid uniqueidentifier,
    @keywordid uniqueidentifier,
    @id uniqueidentifier;
  declare @keyworddata table (keywordid uniqueidentifier);

  set @id = (select KeywordId  from keywords where KeyName=@keywordName)
  set @itemid =(select itemId from Items where ItemID = @itemid);

  if not exists(select keyname from keywords where KeyName = @keywordName)
  begin
    insert into Keywords(KeywordId,KeyName)
    output inserted.KeywordId into @keyworddata(keywordid)
    values (newid(),@keywordName);

    select @keywordid = keywordid from @keyworddata;

    insert into Keywordsitems(KeywordId,ItemId)
    values (@keywordid,@itemid);
  end
  else
  begin
    update keywords set KeyName=@keywordName where KeywordName= @keywordName;
    insert into KeywordsResources(KeywordId,itemId) values (@id,@itemid);       
  end
end
4

1 回答 1

0

您可以使用 TOP 1 来解决此问题。

例如,

...
set @id = (select top 1 KeywordId  from keywords where KeyName=@keywordName)
set @itemid =(select top 1 resourcedatabaseId from Items where ItemID = @itemid); 
...
于 2012-06-27T18:31:35.620 回答