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

Posted zhchsh

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用表变量或临时表遍历数据相关的知识,希望对你有一定的参考价值。

-- 方法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

 

以上是关于使用表变量或临时表遍历数据的主要内容,如果未能解决你的问题,请参考以下文章

MySQL存储过程循环遍历变量并插入临时表

SQL Server 表变量和临时表的区别

表变量

SQL Server遍历表的几种方法

SQL Server遍历表的几种方法

SQL Server 中的临时表使用