June 2008
Sun Mon Tue Wed Thu Fri Sat
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30          
Search

 
Catagories
Archives
Recent Entries
Links
RSS
update with var assignment
Catagory: sql server · This Entry · Comment(0) · eMail entry · Google
April 21, 2005 03:10 PM

sql server

here's an example of how you can perform a variable assignment in an sql update statement. each row processed by the update *also* performs the assignment.

the key is to use this syntax...

SET @x = MyIntegerColumn = @x + 1

this example just increments a value - so each row updated gets a higher value (most cases you would use an index for such a task).


-- create a table:
USE tempdb
GO

CREATE TABLE MyTable (
MyTableID int NULL,
[Name] varchar(35) NOT NULL
)

-- populate some data
INSERT MyTable ([Name]) VALUES ('Jamie')
INSERT MyTable ([Name]) VALUES ('David')
INSERT MyTable ([Name]) VALUES ('Harold')
GO

-- populate MyTableID
DECLARE @vKeyCounter int
SET @vKeyCounter = (SELECT ISNULL(MAX(MyTableID), 0) FROM MyTable)
UPDATE MyTable
SET @vKeyCounter = MyTableID= @vKeyCounter + 1
WHERE MyTableID IS NULL
OPTION (MAXDOP 1)

-- View the results
SELECT *
FROM MyTable





Comments

Post a comment
Name:


Email Address:


URL:


Comments: