The same question has been asked for MySQL here, anyway that syntax doesn’t work in SQL Server.
I paste the sample from that question (by simplifying it) here because it explains what I need very well.
DECLARE @t1 integer
SET @t1=0;
-- MyTable is a simple Table with 2 fields "MyID" and "MyValue"
insert into MyTable
SELECT @t1 := @t1+1, --this "should" work in MySQL
MyAnotherValue
FROM AnotherTable
Is there a way to achieve the same in SQL Server (without using a cursor)?
Note: this is a to be run once query, it is a maintenance query, so race conditions and locks are not an issue.
This will work, even if you run it more than once:
The
isnull()function covers the case whenMyTableis empty