简体   繁体   English

T-SQL:合并或向上插入子表

[英]T-SQL: merge or upsert child table

I have three tables with data as shown in the following screenshot: 我有三个数据表,如以下屏幕快照所示:

在此处输入图片说明

I have a working MERGE statement for the Users table that is sent to the SQL Server from C#. 我有一个有效的MERGE语句,用于从C#发送到SQL Server的Users表。 The MERGE statement correctly merges data into the ICS_USERS table. MERGE语句正确地将数据合并到ICS_USERS表中。 The #temp table is also created and populated in C#: #temp表也​​已创建并用C#填充:

MERGE INTO ICS_Users AS Target 
USING #temp AS Source ON TARGET.USerID = Source.UserId 

WHEN MATCHED THEN 
    UPDATE 
    SET TARGET.UserName = Source.UserName, TARGET.Active = Source.Active 

WHEN NOT MATCHED THEN 
    INSERT(UserName, Active, UserInitials) 
    VALUES(Source.UserName, Source.Active, Source.UserInitials)

I want to allow the user to add/change/delete the role for a user and send in the MERGE statement to handle it. 我想允许用户添加/更改/删除用户角色,并发送MERGE语句来处理它。 Note that the user will only ever be allowed to change a single user at one time. 请注意,用户一次只能更改一个用户。

How do I change the merge statement to account for the Role and User/Role associative table? 如何更改合并语句以说明角色和用户/角色关联表?

You can follow these steps to achieve this. 您可以按照以下步骤来实现。

  1. Create a stored procedure which will accept all the input parameters which are required to join, insert, update and delete the values using source and target. 创建一个存储过程,该过程将接受使用源和目标连接,插入,更新和删除值所需的所有输入参数。 Make all parameter optional or null able so that you can run your merge even without input values. 使所有参数可选或为null,以便即使没有输入值也可以运行合并。

  2. Insert all these values in a table variable which will have same column as your target tables along with the same data type. 将所有这些值插入表变量中,该变量将与目标表具有相同的列以及相同的数据类型。

  3. Use your actual source table and along with table variable and union them and then use the output in merge logic. 使用实际的源表以及表变量并将其合并,然后在合并逻辑中使用输出。

This will handle your both requirement in single merge statement. 这将在单个merge语句中满足您的两个要求。 Even when you input columns will be null first query in union will always have values to suffice the merge logic. 即使您输入的列为空,联合中的第一个查询也将始终具有足以满足合并逻辑的值。

Try if this will not work comment and I will provide you sql script. 请尝试一下,如果这行不通,我将为您提供sql脚本。 Here I am not providing sql intentionally so that at least you can read and try by your self and write the logic in sql. 在这里,我并不是故意提供sql,因此至少您可以自己阅读和尝试并在sql中编写逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM