Site Search:
Sign in | Join | Help
4Penny.net

SQL Server (T-SQL)

Comments and notes on SQL Server 2000, 2005, and T-SQL

Simple Code Example for a Cursor and an ID Column Insert

I frequently get asked how to code an insert that has an ID column that increments. There are a couple of workarounds for this lamentable lapse, but here's how to do it with a cursor.

DECLARE @itemnmbr VARCHAR(31)
DECLARE @intCounter INT


SET @intCounter = 1


DECLARE curName CURSOR KEYSET FOR 
 select TOP 5 itemnmbr
  from iv00101


OPEN curName


FETCH NEXT FROM curName INTO @itemnmbr 
WHILE (@@fetch_status = 0)
BEGIN
 INSERT INTO myTable (idColumn, dataColumn) VALUES (@intCounter,@itemnmbr)
 SET @intCounter = @intCounter + 1


 FETCH NEXT FROM curName INTO @itemnmbr 
END


CLOSE curName
DEALLOCATE curName
GO

Comments

No Comments

About Steve Gray

Steve is a seasoned (translate: old) developer in VB and ASP.NET. He spends most of his time in Dynamics GP, writing custom mods for consulting firms. Crystal reports, eConnect, VS Tools for Dynamics... anything that comes along.