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
  • 相关阅读:
    使用dbms_metadata.get_ddl遇到ORA-31603
    oracle得到建表语句
    Linux性能优化和监控系列(一)——top工具
    Oracle在Linux下的性能优化
    地址跳转问题
    无法对 数据库'UDS' 执行 删除,因为它正用于复制
    [.net 多线程]SpinWait
    [.net 多线程 ]ReaderWriterLock
    [.net 多线程]Barrier
    [.net 多线程]CountdownEvent
  • 原文地址:https://www.cnblogs.com/zhchsh/p/9087274.html
Copyright © 2011-2022 走看看