带有TVP多个值的T-SQL UPSERT表

时间:2013-02-01 04:42:15

标签: tsql sql-server-2012 upsert table-valued-parameters

我使用SQL Server 2012和T-SQL作为查询语言。

我需要帮助更新/插入[cross_function_user]中的多个列,使用一个作为参数(@userGroupID)传递的ID值和许多函数id。它们是C#中的List,并作为表值参数传递给sproc - 只有一列int,名为Item。

ALTER PROCEDURE [whatever]
    @userGroupID INT,
    @listID AS IntList READONLY
AS
BEGIN   
        SET NOCOUNT ON;
    MERGE INTO [dbo].[cross_function_user] USING @listID
    ON [dbo].[cross_function_user].id_group_user = @userGroupID
    WHEN MATCHED THEN
        UPDATE SET [cross_function_user].id_group_user = @userGroupID,
                   [cross_function_user].id_function = (SELECT Item FROM @listID)
    WHEN NOT MATCHED THEN
        INSERT (id_group_user, id_function) 
        VALUES (@userGroupID, (SELECT Item FROM @listID) );

END

首先,它的错误'子查询返回了多个结果'当然,但我缺乏重写这个的技巧,而且我不确定我的upsert是否正确写入。任何帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分:2)

试试这个:

您需要使用TVP中列的名称替换YourColumn。

ALTER PROCEDURE [whatever]
@userGroupID INT,
@listID AS IntList READONLY
AS
BEGIN   
    SET NOCOUNT ON;
    MERGE INTO [dbo].[cross_function_user] USING @listID
    ON [dbo].[cross_function_user].id_group_user = @userGroupID
    WHEN MATCHED THEN
        UPDATE SET [cross_function_user].id_function = S.YourColumn
    WHEN NOT MATCHED THEN
        INSERT (id_group_user, id_function) 
        VALUES (@userGroupID, S.YourColumn);

END