SQL SERVER 循环语句示例
时间: 2024-09-04 22:03:55 浏览: 113
SQL Server 提供了几种循环语句,其中最常用的是`WHILE`和`REPEAT...UNTIL`循环,以及递归查询如`CURSOR`。以下是简单的例子:
1. `WHILE`循环:
```sql
DECLARE @i INT = 0;
WHILE @i < 5
BEGIN
SELECT 'This is iteration ' + CAST(@i AS VARCHAR(10));
SET @i = @i + 1;
END;
```
这个循环会执行五次,每次打印一条迭代信息。
2. `REPEAT...UNTIL`循环:
```sql
DECLARE @j INT = 1;
REPEAT
BEGIN
SELECT 'This is iteration ' + CAST(@j AS VARCHAR(10));
SET @j = @j + 1;
END
UNTIL @j > 5;
```
类似地,这个循环会在变量`@j`小于6时持续执行并打印迭代信息。
3. 使用`CURSOR`的递归查询(假设有一个名为`GetParents`的自连接函数用于查找所有祖先节点):
```sql
DECLARE @current INT = (SELECT id FROM MyTable WHERE parent_id IS NULL);
DECLARE @cursor CURSOR FOR
WITH RECURSIVE CTE(id, level) AS (
SELECT id, 1
FROM MyTable
WHERE id = @current
UNION ALL
SELECT mt.id, mt.level + 1
FROM MyTable mt
JOIN CTE cte ON mt.parent_id = cte.id
)
SELECT *
FROM CTE;
OPEN @cursor;
FETCH NEXT FROM @cursor INTO @current, @level;
WHILE @@FETCH_STATUS = 0
BEGIN
-- 打印当前行
FETCH NEXT FROM @cursor INTO @current, @level;
END
CLOSE @cursor;
DEALLOCATE @cursor;
```
这个例子通过递归游标获取树形结构的所有节点。
阅读全文