Last active
January 12, 2021 19:37
-
-
Save stevewithington/80384f08a0ae75c6ec0ebd7254b6f118 to your computer and use it in GitHub Desktop.
SQL: Update a table with Common Table Expression (CTE)
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
/* | |
Example of how to update a table in SQL using a Common Table Expression (CTE) | |
*/ | |
USE [SomeTable] | |
GO | |
;WITH cte AS ( | |
SELECT te.LandEntityId, te.BirthDate, te.BirthDateId, dd.DateId | |
FROM TypedEntity te | |
LEFT JOIN [SomeOtherTable].[dbo].[DimDate] dd | |
ON dd.Date = te.BirthDate | |
) | |
UPDATE cte | |
SET cte.BirthdateId = cte.DateId; | |
/* Another Example: Prepend a zero to a column if the length is less than 2 characters */ | |
USE [SomeTable] | |
GO | |
;WITH cte AS ( | |
SELECT SomeColumn | |
FROM TypedEntity te | |
WHERE LEN(SomeColumn) < 2 | |
) | |
UPDATE cte | |
SET cte.SomeColumn = CONCAT('0', cte.SomeColumn); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment