Saturday, 9 August 2014

loop through a table in SQL Server

Create table

CREATE TABLE tbl_Sample
(
     ID      int identity (1,1)
    ,Name    varchar(50)
)

Loop through Code

DECLARE @minID int
 -- get the first record
SELECT @minID = min(ID) FROM tbl_Sample
 -- loop until we have no more records
WHILE @minID is NOT NULL
BEGIN
    -- do actual work, for instance, get the Name and Address for this ID
    SELECT Name FROM tbl_Sample WHERE ID = @minID
     -- get the next record
    SELECT @minID = min(ID) FROM tbl_Sample WHERE @minID < ID
END

No comments:

Post a Comment