SQL 错误:子查询返回了 1 个以上的值

SQL 错误:子查询返回了 1 个以上的值

问题描述:

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

I'm getting keyword input in a textbox like test,check,..etc.I insert those keyword as individual rows in my database on checking if it exists,if exists update or else insert it.This keywordid and item that represents to this id should be inserted into bridge table.On inserting existing keyword it throws errors:

子查询返回了 1 个以上的值.当子查询跟在 =, !=, <, <= , >, >= 或当子查询用作表达式时,这是不允许的.

无法将 NULL 值插入到列 'KeywordId'、表 'dbo.Keywordsitems' 中;列不允许空值.插入失败.

我正在使用下面的存储过程

I'm using the below stored procedure

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

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

You can use TOP 1 to resolve this.

例如,

...
set @id = (select top 1 KeywordId  from keywords where KeyName=@keywordName)
set @itemid =(select top 1 resourcedatabaseId from Items where ItemID = @itemid); 
...