复制代码
1 -- 方法2:使用表变量
2 -- 声明表变量
3 DECLARE @temp TABLE--类似 declare @a int;
4 (
5 empid INT,
6 firstname NVARCHAR(10),
7 lastname NVARCHAR(20)
8 );
9
10 -- 将源表中的数据插入到表变量中
11 INSERT INTO @temp(empid, firstname, lastname )
12 SELECT empid,firstname,lastname FROM HR.Employees
13 ORDER BY empid;
14
15 -- 声明变量
16 DECLARE
17 @empid AS INT,
18 @firstname AS NVARCHAR(10),
19 @lastname AS NVARCHAR(20);
20
21 WHILE EXISTS(SELECT empid FROM @temp)
22 BEGIN
23 -- 也可以使用top 1
24 SET ROWCOUNT 1
25 SELECT @empid= empid, @firstname= firstname,@lastname= lastname FROM @temp;--查询
26 UPDATE HR.Employees SET fullname= @firstname+' '+@lastname WHERE empid=@empid;--更新
27 SET ROWCOUNT 0
28
29 DELETE FROM @temp WHERE empid=@empid; --删除
30 END
set rowcount * 使 SQL Server 在返回指定的行数之后停止处理查询。
要将此选项设置为 off 以便返回所有的行,请将 SET ROWCOUNT 指定为 0。
复制代码
回到顶部
使用临时表
临时表也可以实现表变量的功能,所以我们也可以使用临时表来实现这个需求,代码如下。
复制代码
1 -- 方法3:使用临时表
2 -- 创建临时表
3 IF OBJECT_ID('tempdb.dbo.#tempemployees','U') IS NOT NULL DROP TABLE dbo.#tempemployees;
4 GO
5
6 SELECT empid,firstname,lastname
7 INTO dbo.#tempemployees
8 FROM HR.Employees
9 ORDER BY empid;
10
11 --SELECT * FROM dbo.#tempemployees;
12
13 -- 声明变量
14 DECLARE
15 @empid AS INT,
16 @firstname AS NVARCHAR(10),
17 @lastname AS NVARCHAR(20);
18
19 WHILE EXISTS(SELECT empid FROM dbo.#tempemployees)
20 BEGIN
21 -- 也可以使用top 1
22 SET ROWCOUNT 1
23 SELECT @empid= empid, @firstname= firstname,@lastname= lastname FROM dbo.#tempemployees;
24 UPDATE HR.Employees SET fullname= @firstname+' '+@lastname WHERE empid=@empid;
25 SET ROWCOUNT 0
26
27 DELETE FROM dbo.#tempemployees WHERE empid=@empid;
28 END