Skip to content

Instantly share code, notes, and snippets.

@bhrgu
Created October 30, 2017 13:29
Show Gist options
  • Save bhrgu/936acd3cec92e5292b4287aaabf7bdbe to your computer and use it in GitHub Desktop.
Save bhrgu/936acd3cec92e5292b4287aaabf7bdbe to your computer and use it in GitHub Desktop.
An example of using UPDATE with JOIN
USE TestDatabase
/* Create tables */
CREATE TABLE [dbo].[TParent](
[id] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
[name] [nvarchar](300) NULL
)
CREATE TABLE [dbo].[TChild](
[id] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
[name] [nvarchar](300) NULL,
[parent_id] [int] NOT NULL FOREIGN KEY REFERENCES [dbo].[TParent](id)
)
/* Filling data (incomplete for the child table */
INSERT INTO [dbo].[TParent] (name)
VALUES ('Record_1'),
('Record_2')
INSERT INTO [dbo].[TChild] (name, parent_id)
VALUES ('Record_1_child ', 1),
(NULL, 2)
/* Update the child table rows with data missing */
UPDATE TC
SET TC.name = TP.name + '_child'
FROM [dbo].[TChild] TC
LEFT JOIN [dbo].[TParent] TP on TC.parent_id = TP.id
WHERE TC.name IS NULL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment