sql for loop

Alter PROCEDURE dbo.sp_InsertRecords
AS
Declare @id int
-- first we'll pull some records out of our table.
DECLARE CursorQuery CURSOR FOR
            SELECT ID FROM myTable WHERE MyRecord > 15
OPEN CursorQuery
-- we're going to fetch our record into the ID variable which we'll use for inserting a related record.
FETCH NEXT FROM CursorQuery
INTO @ID
PRINT 'Record Status' +  CAST(@@FETCH_STATUS as varchar)
WHILE @@FETCH_STATUS = 0
BEGIN
-- now insert the id from the main table into the related table.
            INSERT INTO
                        RelatedTable
                        (relatedID)
            VALUES
                        (@id)                   
            FETCH NEXT FROM CursorQuery
            INTO @ID
END
CLOSE CursorQuery
DEALLOCATE CursorQuery
RETURN

你可能感兴趣的:(loop)