码迷,mamicode.com
首页 > 其他好文 > 详细

使用表变量或临时表遍历数据

时间:2018-05-25 13:57:52      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:arc   count   top   delete   col   使用   char   声明变量   int   

-- 方法1:使用表变量
  -- 声明表变量
  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

  -- 方法2:使用临时表
  -- 创建临时表
  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

 

使用表变量或临时表遍历数据

标签:arc   count   top   delete   col   使用   char   声明变量   int   

原文地址:https://www.cnblogs.com/zhchsh/p/9087274.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!