SQL Server loop - how do I loop through a set of records

前端 未结 8 1498
慢半拍i
慢半拍i 2020-11-28 17:54

how do I loop through a set of records from a select?

So say for example I have a few records that I wish to loop through and do something with each record. Here\'s

8条回答
  •  被撕碎了的回忆
    2020-11-28 18:30

    By using cursor you can easily iterate through records individually and print records separately or as a single message including all the records.

    DECLARE @CustomerID as INT;
    declare @msg varchar(max)
    DECLARE @BusinessCursor as CURSOR;
    
    SET @BusinessCursor = CURSOR FOR
    SELECT CustomerID FROM Customer WHERE CustomerID IN ('3908745','3911122','3911128','3911421')
    
    OPEN @BusinessCursor;
        FETCH NEXT FROM @BusinessCursor INTO @CustomerID;
        WHILE @@FETCH_STATUS = 0
            BEGIN
                SET @msg = '{
                  "CustomerID": "'+CONVERT(varchar(10), @CustomerID)+'",
                  "Customer": {
                    "LastName": "LastName-'+CONVERT(varchar(10), @CustomerID) +'",
                    "FirstName": "FirstName-'+CONVERT(varchar(10), @CustomerID)+'",    
                  }
                }|'
            print @msg
        FETCH NEXT FROM @BusinessCursor INTO @CustomerID;
    END
    

提交回复
热议问题