New and Changed SQL Server 2005 commands: Part1

I know I don’t often talk about code, but I have recently had the good fortune to get back into playing around with the new version of SQL Server 2005. I think I’m going to do a few small posts on some of the new things I’ve found that I like.

Insert and Merge, finally your can ‘Upsert’!

Upsert is a mythical feature where you can insert and update data with one command. It's not quite in one command but the effect is the same with a simple set of syntax.

MERGE INTO DavesTable

            USING DavesTempTable

                        ON DavesTable.MatchingField1 = DavesTempTable.MatchingField1

WHEN MATCHED THEN

            UPDATED UpdatedField1 = DavesTempTable.UpdatedField1

WHEN NOT MATCH THEN

            INSERT VALUES(DavesTempTable.MatchingField1, DavesTempTable.UpdateField1)

Although it’s nice to finally have this feature and the syntax is simple and elegant I’m wondering if many people will actual use it in anger.

UPDATE: August 2008: Well the MERGE command didn't finally make it until SQL Server 2008. It didn't make 2005 and was pulled in the RTM version.

Now the TOP command has always been a great feature but what has always been a right pain is that it has to be a constant in SQL Server 2000 which has really limited it’s use.

Now this syntax is valid!

-- show the first x products names in alphabetical order.

DECLARE @x bigint

SET @x = 25

SELECT TOP (@x) ProductID, Name

FROM Product

ORDER BY NAME

Just like the previous version of the TOP command it was well used in scalar statements. With the ability to pass the value to the statement from the outside I can see this going to be a very powerful new feature used for reporting especially as the PERCENT suffix is still valid. The only departure from the previous version is that you will need to use brackets if the value is a variable, use a constant and you won’t need them.

This article is part of the GWB Archives. Original Author: Dave Oliver

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.