---
# System prepended metadata

title: SQL 迴圈作法
tags: [SQL]

---

# SQL 迴圈作法
###### tags: `SQL`

## Table 資料需定義 RowNumber

#### 將結果暫存至 #TargetTable
```
Select ROW_NUMBER() OVER(ORDER BY Id) AS ROWID, Name, Area, Country
Into #TargetTable
From tblCity  
```

## 定義 Count，使用 While 迴圈 Go Go !

#### 使用 RowNumber 比對
```
--跑迴圈
Declare @WhileTableCount int = 1;
Declare @TabelCount int = (SELECT COUNT(*) FROM #MembersOfEvent)
    
WHILE @WhileTableCount <= @TabelCount
BEGIN	

    @CityName nvarchar(max) = ( Select Name From #MembersOfEvent Where ROWID = @WhileTableCount )
    @BelongArea nvarchar(max) = ( Select Area From #MembersOfEvent Where ROWID = @WhileTableCount )
    
    --別忘了最後 WhileTableCount 要 +1 喔，不然 GG 了
    SET @WhileTableCount = @WhileTableCount + 1
    
END
```
