UPDATE/INSERT syntax trick

by Allan Svelmøe Hansen June 08, 2008 09:17

A little trick you can use with an update or insert is an automatic assignment.
For example at times I've had to update all rows in a (temporay) table with an consecutive number and a fast way of doing this is utilizing this technique:

DECLARE @I INT
SET 
@I 0
UPDATE Table_1
SET @I MyID @I 1
 

This example instantiates an interger (I) to the value 0. Then I update a table where I set an ID column to the value of I + 1, but at the same time I set my I variable to the value of MyID. This means that the first row will get the value 1 into MyID and the second will get 2 and so forth.

And of course this example is very simple, and in such a case one might as well just use identity. However because you can make any calculations you want, and because it does not have to be an integer data type - you can use this for various situations.

It just goes to show that T-SQL syntax allows for playing around.

Bookmark and Share DotnetKicks dotnetshoutout

Tags: ,

SQL

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.6.1.0
Theme by Mads Kristensen | Modified by Mooglegiant

About:
Allan Svelmøe Hansen

My real name is Allan Svelmøe Hansen.
I live in Denmark, where I work as a developer for hedal:kruse:brohus using SQL Server and the .NET framework since 2004.
My primary fields of expertise is back-end data integration, database design and optimization.


       View Allan Svelmøe Hansen's profile on LinkedIn     

Disclaimer

The opinions expressed herein are my own personal opinions and thoughts and does not represent my employers view in any way, nor are my results guaranteed for all situations.
Content is presented "as is", with no warranty.