Andrew On Tech

tech tricks, hack, useful links, productivity tips, developers tools review and many more

Syntax Sugar in SQL Server 2005

Posted by mymuss on July 25, 2008

1. Using OUTPUT clause:

DECLARE @NewKeys TABLE (
  [Key1]    UNIQUEIDENTIFIER NOT NULL,
  [Key2]    UNIQUEIDENTIFIER NOT NULL
);

UPDATE [XTable]
SET [Key2] = NEWID()
  OUTPUT inserted.[Key1], inserted.[Key2]
  INTO @NewKeys
WHERE [Key2] IS NULL;

Only updated rows go to @NewKeys table, of course a temporary or even a regular table can be used instead of table variable. No need for triggers.

2. Using JOIN with UPDATE:

UPDATE [x]
SET [x].[Key1] = [y].[Key1]
FROM [XTable] AS [x] INNER JOIN [YTable] AS [y]
ON [x].[Key2] = [y].[Key2]

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.