Sql插入错误 - "子查询返回的值超过1"

时间:2014-07-18 13:57:05

标签: sql sql-server

在下面的代码中,我使用逗号传递多个值,分隔给@i_CustomerGroupID,将一个值传递给@ i_LocationID.In,我面临一个问题“子查询返回的值超过1。当子查询跟随=时,不允许这样做! =,<,< =,>,> =或当子查询用作表达式时。 该声明已被终止。“。请帮助我解决问题。

ALTER PROCEDURE [dbo].[spInsertCustomerGroupLocationMap]
    -- Add the parameters for the stored procedure here
    @i_LocationID int,
    @i_CustomerGroupID varchar(100)

    --WITH ENCRYPTION
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    IF NOT EXISTS (SELECT 1 FROM CustomerGroupLocationMap WHERE LocationID = @i_LocationID AND CustomerGroupID = @i_CustomerGroupID)
    BEGIN

        INSERT INTO CustomerGroupLocationMap (LocationID, CustomerGroupID) VALUES (@i_LocationID, (SELECT * FROM dbo.CSVToTable(@i_CustomerGroupID)));

    END
END

3 个答案:

答案 0 :(得分:1)

您想使用insert . . . select

    INSERT INTO CustomerGroupLocationMap(LocationID, CustomerGroupID) 
        SELECT @i_LocationID, t.*
        FROM dbo.CSVToTable(@i_CustomerGroupID) t;

您的函数dbo.CSVToTable()返回多个值(我假设只有一列)。正确的语法是insert . . . select

作为一个说明,实际上不需要insert . . . values。即使只有常数,也可以使用insert . . . select

答案 1 :(得分:0)

IF NOT EXISTS (SELECT TOP 1 FROM CustomerGroupLocationMap WHERE LocationID = @i_LocationID AND CustomerGroupID = @i_CustomerGroupID)
BEGIN

    INSERT INTO CustomerGroupLocationMap (LocationID, CustomerGroupID) VALUES (@i_LocationID, (SELECT * FROM dbo.CSVToTable(@i_CustomerGroupID)));

END

答案 2 :(得分:0)

您需要重写存在的查询和插入查询 -

IF NOT EXISTS (SELECT 1 FROM CustomerGroupLocationMap WHERE LocationID = @i_LocationID AND CustomerGroupID IN (SELECT *
    FROM dbo.CSVToTable(@i_CustomerGroupID) ))
BEGIN

    INSERT INTO CustomerGroupLocationMap (LocationID, CustomerGroupID) 
    SELECT @i_LocationID, i.* FROM dbo.CSVToTable(@i_CustomerGroupID) i;

END