SQL For Loop, Using Cursor



/** Declare Variables For Cursor to Store Values **/
DECLARE @FirstName NVARCHAR(50), @Age INT, @ID NVARCHAR(50), @RegisterDate DATETIME

/** Confirm tempTable Is Deleted **/
DROP Table #TempTable1
DROP Table #TempTableName

/** Using Select Result Insert Value To Create A TempTable**/
SELECT * INTO #TempTableName
FROM
(
    /** Create a Table With Value Generated By My Self **/
    SELECT * FROM 
    (VALUES 
        /** First Value, Second Value In A Row**/
        ('David', 25),
        ('Brown', 26),
        ('Alex', 22)

    ) /** First Column Name, Second Column Name**/
    as E(FirstName, Age)
) N

SELECT * INTO #TempTable1
FROM 
(
    SELECT a.FirstName, a.Age, (right(NEWID(), 8)) as ID, (GETDATE()) as RegisterDate FROM #TempTableName a
) b

/*** SQL Using Cursor to Do a Foreach Loop, Load Every Row ***/
DECLARE Cursor1 CURSOR READ_ONLY
FOR
                    /** Data Source **/
                    SELECT * FROM #TempTable1

/* Put Data Into Cursor */
OPEN Cursor1

/* Put Data From Cursor Into Variables */
FETCH NEXT FROM Cursor1 INTO
@FirstName, @Age, @ID, @RegisterDate

WHILE @@FETCH_STATUS = 0
BEGIN
    DECLARE @newID nvarchar(50) = right(NEWID(), 8)
    PRINT CONCAT(@newID,  ' | ', @FirstName)

    /* Execute Insert */
    --INSERT INTO User_Info
    --                      (
    --                          FirstName, Age, ID, RegisterDate
    --                      )

    --                      VALUES
    --                      (
    --                          @FirstName, @Age, @ID, @RegisterDate
    --                      )

    /* Next Row,Put Value From Cursor Into Variables Again */
    FETCH NEXT FROM Cursor1 INTO
    @FirstName, @Age, @ID, @RegisterDate
END

/* Close Cursor */
CLOSE Cursor1

/* Release Cursor */
DEALLOCATE Cursor1
#SQL #cursor #for #foreach #Loop






你可能感興趣的文章

C# class, object, method, constructors, getter, setter, static

C# class, object, method, constructors, getter, setter, static

API 留言板練習-Part 2 : 前端串 API

API 留言板練習-Part 2 : 前端串 API

相似CSS語法及其差異 補

相似CSS語法及其差異 補






留言討論