Created
February 11, 2017 00:49
-
-
Save davghouse/c0e80cb43c43940cbfc8a153f96ccd3d to your computer and use it in GitHub Desktop.
Copy Province procedure for Rooted World database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE PROCEDURE [dbo].[CopyProvince] | |
@id INT | |
AS | |
BEGIN | |
SET NOCOUNT ON; | |
SET XACT_ABORT ON; | |
BEGIN TRAN; | |
DECLARE @ProvinceIDPairs TABLE ( | |
ExistingID INT NOT NULL UNIQUE, | |
InsertedID INT NOT NULL UNIQUE | |
); | |
MERGE INTO [dbo].[Provinces] AS Target | |
USING ( | |
SELECT * | |
FROM [dbo].[Provinces] | |
WHERE [ID] = @id | |
) AS Source | |
ON 1 = 0 | |
WHEN NOT MATCHED BY TARGET THEN | |
INSERT ( | |
[NationID], | |
[Name], | |
[Motto]) | |
VALUES ( | |
Source.[NationID], | |
Source.[Name], | |
Source.[Motto]) | |
OUTPUT Source.[ID], Inserted.[ID] | |
INTO @ProvinceIDPairs; | |
MERGE INTO [dbo].[Residents] AS Target | |
USING ( | |
SELECT | |
copy.*, | |
j0.InsertedID j0InsertedID | |
FROM [dbo].[Residents] copy | |
JOIN @ProvinceIDPairs j0 | |
ON copy.[ProvinceID] = j0.ExistingID | |
) AS Source | |
ON 1 = 0 | |
WHEN NOT MATCHED BY TARGET THEN | |
INSERT ( | |
[ProvinceID], | |
[Name]) | |
VALUES ( | |
j0InsertedID, | |
Source.[Name]); | |
COMMIT TRAN; | |
END; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment