Created
July 20, 2012 11:59
-
-
Save bendras/3150354 to your computer and use it in GitHub Desktop.
SQL Copy 2 tables with relationship
This file contains hidden or 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
-- 1. Create New tables with additional column targeting to table data is being copied from. | |
-- [SocialInteraction].[StatusOutboxId] is primary key value from [StatusOutbox].[StatusOutboxId]. | |
-- [SocialInteraction_Service].[UserTenantSocialAuthStatusOutboxId] is primary key value from [UserTenantSocialAuth_StatusOutbox].[UserTenantSocialAuth_StatusOutboxId] table. | |
-- 2. Copy data from 1-st table | |
INSERT INTO SocialInteraction | |
([TenantId] | |
,[UserId] | |
,[Message] | |
,[InteractionTypeId] | |
,[SendAt] | |
,[CreatedOn] | |
,[ToUserName] | |
,[ToUserForeignId] | |
,[InReplyToShareForeignId] | |
,[Subject] | |
,[LinkName] | |
,[LinkUrl] | |
,[ImageUrl] | |
,[Caption] | |
,[Description] | |
,[StatusOutboxId]) | |
SELECT | |
so.TenantId AS [TenantId], | |
so.CreatedById AS [UserId], | |
so.[Message] AS [Message], | |
1 AS [InteractionTypeId], | |
so.SendAt AS [SendAt], | |
so.CreatedOn AS [CreatedOn], | |
NULL AS [ToUserName], | |
NULL AS [ToUserForeignId], | |
NULL AS [InReplyToShareForeignId], | |
NULL AS [Subject], | |
NULL AS [LinkName], | |
NULL AS [LinkUrl], | |
NULL AS [ImageUrl], | |
NULL AS [Caption], | |
NULL AS [Description], | |
so.[StatusOutboxId] as [StatusOutboxId] | |
FROM StatusOutbox AS so; | |
-- 3. Copy data from 2-nd table including relationship to previous records. | |
INSERT INTO [SocialInteraction_Service] | |
([SocialInteractionId] | |
,[SendingStateId] | |
,[SocialServiceTypeId] | |
,[UpdatedOn] | |
,[ErrorId] | |
,[UserTenantSocialAuthStatusOutboxId]) | |
SELECT | |
si.SocialInteractionId AS [SocialInteractionId], | |
CASE WHEN sout.ErrorDateTime IS NULL THEN 1 ELSE 2 END AS [SendingStateId], | |
utsa.ServiceId AS [SocialServiceTypeId], | |
sout.ErrorDateTime AS [UpdatedOn], | |
sout.ErrorId AS [ErrorId], | |
sout.UserTenantSocialAuth_StatusOutboxId AS [UserTenantSocialAuthStatusOutboxId] | |
FROM [SocialInteraction] AS si | |
JOIN StatusOutbox AS so ON so.StatusOutboxId = si.StatusOutboxId | |
JOIN UserTenantSocialAuth_StatusOutbox AS sout ON sout.StatusOutboxId = so.StatusOutboxId | |
JOIN UserTenant_SocialAuth AS utsa ON utsa.UserSocialAuthId = sout.UserSocialAuthId; | |
-- 4. Now you can drop the additional copumns. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment