I'm currently working on a stored procedure in T-SQL on SQL Server 2012. The task is really tricky: I need to merge (insert,update,delete) entries in multiple tables.
To facilitate, I try to explain my problem with 2 tables. I use Dapper in C# in an ASP.NET 4.5 MVC application and can control my Front-End. I'm passing into the stored procedure 2 Temporary Tables:
Temporary Table Target:
ID | TargetId | TargetGroupId | IsPublic | IsPrivate |
---+----------+---------------+----------+-----------+
0 | 42 | 1 | 0 | 1 |
1 | 0 | 1 | 1 | 0 |
2 | 0 | 1 | 0 | 1 |
Temporary Table Target Countries
ID |CountryId | TargetId |
---+----------+----------+
0 | CA | 42 |
1 | FR | 0 |
2 | AU | 0 |
The TargetId 0 corresponds to a new entry, thus if the TargetId = 0 I want to Insert or Delete an old record not from the list, if the TargetId > 0 I want to Update the record.
The final Result could look like this:
Table Target:
| TargetId | TargetGroupId | IsPublic | IsPrivate |
+----------+---------------+----------+-----------+
| 42 | 1 | 0 | 1 |
| 93 | 1 | 1 | 0 |
| 94 | 1 | 0 | 1 |
Table Country:
CId |CountryId | TargetId |
-----+----------+----------+
34 | CA | 42 |
35 | FR | 93 |
36 | AU | 94 |
So the new TargetId should be stored in Country as well. My current TSQL script looks like this:
DECLARE @TargetGroupId = 1;
MERGE [MySchema].[Target] AS [A]
USING @Targets AS [B]
ON ([A].TargetId = [B].TargetId)
WHEN NOT MATCHED BY TARGET THEN
INSERT (TargetGroupId, IsPrivate, IsPublic)
VALUES (@TargetGroupId, [B].IsPrivate, [B].IsPublic)
-- Desired behaviour: doesn't work unfortunately...
-- OUTPUT inserted.TargetId, [B].ID
-- INTO #tmp;
WHEN MATCHED THEN
UPDATE
SET [A].IsPrivate = [B].IsPrivate, [A].IsPublic = [B].IsPublic
WHEN NOT MATCHED BY SOURCE AND [A].TargetGroupId = @TargetGroupId
THEN DELETE;
This SQL script works fine for my table Target, but how can I update my second table Countries?
Do you know how solve this issue, thus to Insert, Update, Delete in a Merge Statement including several tables?
Thank you very much!!
1条答案
按热度按时间qyuhtwio1#