Skip to content

Instantly share code, notes, and snippets.

@stevewithington
Last active January 12, 2021 19:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevewithington/80384f08a0ae75c6ec0ebd7254b6f118 to your computer and use it in GitHub Desktop.
Save stevewithington/80384f08a0ae75c6ec0ebd7254b6f118 to your computer and use it in GitHub Desktop.
SQL: Update a table with Common Table Expression (CTE)
/*
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