2014-07-18 111 views
1

在下面的代碼中,我將多個值用逗號分隔到@i_CustomerGroupID和一個值到@ i_LocationID。其中我面臨的問題是「子查詢返回的值超過1 。當子查詢遵循=,!=,<,< =,>,> =或當子查詢用作表達式時,這是不允許的。 聲明已被終止。「。請幫我解決問題。Sql插入錯誤 - 「子查詢返回超過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 

回答

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

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 
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 
相關問題