zoukankan      html  css  js  c++  java
  • T-SQL 循环表的一种方式

    原文来自: https://www.lesg.cn/netdaima/sqlservert-sql/2016-463.html

    SsqlServer 中循环表有几种方式

    1.临时表

    2.游标

    3….

    下面就来说说怎么用临时表格来循环数据

    create table t(
     
    id int not null primary key identity(1,1),
     
    dt datetime not null default(getdate()),
     
    name varchar(100) not null default('')
     
    )
    --测试案例,给表插入数据
    declare @count int ;set @count=0;
    while(@count<100)
    begin
    set @count= @count+1
    insert into t (name) values (NEWID())
    end
    select * from t
    --判断临时表是否存在 如果存在则删除临时表
    if exists(select 1 from tempdb..sysobjects where id=object_id('tempdb..#t_m'))
    begin
     drop table #t_m --删除临时表
    end
    --将数据插入临时表
    select * into #t_m from t 
    --开始循环表数据
     
     declare @tmid int ; -- 创建一个临时变量
    While (exists ( select 1 from #t_m))
    BEGIN
    select top 1 @tmid =id from #t_m --拿出一条数据复制在临时变量里面, 用于待会删除该数据使用
    --
     /*
     好了 在这里使用 @tmid 来操作 该条数据吧
     lesg.cn
     */
    --
    DELETE #t_m WHERE ID=@tmid; --删除一条临时表的数据
    END
    if exists(select 1 from tempdb..sysobjects where id=object_id('tempdb..#t_m'))
    begin
     drop table #t_m --操作结束后删除临时表
    end

    思路如下;
    1.创建临时表格
    2.while 循环临时表; 循环条件是 临时表是否存在
    3. 获取一条临时表的数据; 记得使用top 1 否则数据一多起来性能低到你发疯 获得临时变量,临时变量等于该条数据的ID

    select  top 1 @tmid =id from #t_m

    4.使用临时变量来操作数据
    5.整个循环结束后删除临时表

  • 相关阅读:
    CMU15-445 Project #2
    CMU15-445 Project #1 Buffer Pool
    挂分原因
    「杂谈」关于斜率优化维护凸包
    「题解」GYM 101620J Justified Jungle
    「题解」AGC 052 B Tree Edges XOR
    C++ MT19937 随机数 限制范围
    「题解」Codeforces 348C Subset Sums
    「学习笔记」联赛数论再学习
    「题解」洛谷 P4597 序列sequence
  • 原文地址:https://www.cnblogs.com/wcgsir/p/6181642.html
Copyright © 2011-2022 走看看