1

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

我需要帮助使用作为参数传递的一个 ID 值 (@userGroupID) 和许多函数 ID 来更新/插入 [cross_function_user] 中的多个列。它们是 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 是否以正确的方式编写。任何帮助将不胜感激。

4

1 回答 1

2

Try this:

You need to replace YourColumn with the name of the column in your TVP.

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
于 2013-02-01T06:23:32.640 回答