标签:
在数据库开发过程中,我们经常会碰到要遍历数据表的情形,一提到遍历表,我们第一印象可能就想到使用游标,使用游标虽然直观易懂,但是它不符合面向集合操作的原则,而且性能也比面向集合低。当然,从面向集合操作的角度出发,也有两种方法可以进行遍历表的操作,总结起来,遍历表有下面几种方法。
我的需求是:针对HR.Employees表,新增一列fullname,并取值firstname+lastname。
这个需求本来可以一条sql语句搞定,如下代码所示。但是为了演示表的遍历,我还是使用了这三种方式来实现一下。
USE TSQLFundamentals2008; GO UPDATE HR.Employees SET fullname= firstname+‘ ‘+lastname;
使用游标的代码比较繁琐,概括起来主要有以下几个步骤,声明游标,打开游标,使用游标,关闭游标和释放游标。示例代码如下。
USE TSQLFundamentals2008; GO SELECT * FROM HR.Employees; -- 需求是,新增一列fullname,取值firstname+lastname ALTER TABLE HR.Employees ADD fullname NVARCHAR(30) NULL; GO -- 方法1:游标 -- 声明变量 DECLARE @empid AS INT, @firstname AS NVARCHAR(10), @lastname AS NVARCHAR(20); -- 声明游标 DECLARE C_Employees CURSOR FAST_FORWARD FOR SELECT empid,firstname,lastname FROM HR.Employees ORDER BY empid; OPEN C_Employees; -- 取第一条记录 FETCH NEXT FROM C_Employees INTO @empid,@firstname,@lastname; WHILE @@FETCH_STATUS=0 BEGIN -- 操作 UPDATE HR.Employees SET fullname= @firstname+‘ ‘+@lastname WHERE empid=@empid; -- 取下一条记录 FETCH NEXT FROM C_Employees INTO @empid,@firstname,@lastname; END -- 关闭游标 CLOSE C_Employees; -- 释放游标 DEALLOCATE C_Employees; -- 方法2:使用表变量 -- 声明表变量 DECLARE @temp TABLE ( empid INT, firstname NVARCHAR(10), lastname NVARCHAR(20) ); -- 将源表中的数据插入到表变量中 INSERT INTO @temp(empid, firstname, lastname ) SELECT empid,firstname,lastname FROM HR.Employees ORDER BY empid; -- 声明变量 DECLARE @empid AS INT, @firstname AS NVARCHAR(10), @lastname AS NVARCHAR(20); WHILE EXISTS(SELECT empid FROM @temp) BEGIN -- 也可以使用top 1 SET ROWCOUNT 1 SELECT @empid= empid, @firstname= firstname,@lastname= lastname FROM @temp; UPDATE HR.Employees SET fullname= @firstname+‘ ‘+@lastname WHERE empid=@empid; SET ROWCOUNT 0 DELETE FROM @temp WHERE empid=@empid; END -- 方法3:使用临时表 -- 创建临时表 IF OBJECT_ID(‘tempdb.dbo.#tempemployees‘,‘U‘) IS NOT NULL DROP TABLE dbo.#tempemployees; GO SELECT empid,firstname,lastname INTO dbo.#tempemployees FROM HR.Employees ORDER BY empid; --SELECT * FROM dbo.#tempemployees; -- 声明变量 DECLARE @empid AS INT, @firstname AS NVARCHAR(10), @lastname AS NVARCHAR(20); WHILE EXISTS(SELECT empid FROM dbo.#tempemployees) BEGIN -- 也可以使用top 1 SET ROWCOUNT 1 SELECT @empid= empid, @firstname= firstname,@lastname= lastname FROM dbo.#tempemployees; UPDATE HR.Employees SET fullname= @firstname+‘ ‘+@lastname WHERE empid=@empid; SET ROWCOUNT 0 DELETE FROM dbo.#tempemployees WHERE empid=@empid; END --UPDATE HR.Employees SET fullname=NULL; --SELECT * FROM HR.Employees; --USE TSQLFundamentals2008; --GO --UPDATE HR.Employees SET fullname= firstname+‘ ‘+lastname;
标签:
原文地址:http://www.cnblogs.com/mcgrady/p/4182486.html