zoukankan      html  css  js  c++  java
  • 使用表变量或临时表遍历数据

    -- 方法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
  • 相关阅读:
    做开发的童鞋应该都了解这几款软件
    给文件对比工具自定义快捷键的方法
    C/C++ 编程有哪些值得推荐的辅助工具
    如何用Beyond Compare修改对比文件颜色
    据说这些工具可以提高程序员的工作效率
    遇到Beyond Compare禁止编辑该怎么办
    BZOJ
    周三
    大总结
    周二上午
  • 原文地址:https://www.cnblogs.com/zhchsh/p/9087274.html
Copyright © 2011-2022 走看看