zoukankan      html  css  js  c++  java
  • MSSQL中游标例子纵转横

    /*
    纵向表内容
    f_billno,f_invname
    0001 商品1
    0002 商品A
    0001 商品2
    0001 商品3
    0002 商品B
    0003 商品I
    0003 商品II
    目标效果
    fid,ftext
    0001 商品1商品2商品3
    0002 商品A商品B
    0003 商品I商品II

    以下是SQL语句,用到了临时表和游标的使用。
    */
    --查看源数据
    select f_billno,f_invname from test

    --定义两个临时变量用来保存游标取得的数据
    DECLARE @c varchar(255)
    DECLARE @c1 varchar(255)
    --删除临时表
    if object_id('tempdb..#tmp') is not null drop table #tmp
    --建立临时表及生成数据
    Create Table #tmp(fid varchar(4),ftext varchar(255))
    insert into #tmp
    select f_billno,'' from test group by f_billno
    --取游标数据
    declare cur_test CURSOR FOR
    select f_billno,f_invname from test
    open cur_test
    fetch next from cur_test into @c,@c1
    --第一个循环
    while @@fetch_status=0
    begin
    --重复取数据并生成相应的处理SQL
    exec('update #tmp set ftext=ftext+'''+@c1+' '' where fid='''+@c+'''');
    fetch next from cur_test into @c,@c1
    end
    --显示结果数据
    select * from #tmp
    --关闭游标
    close cur_test
    deallocate cur_test
  • 相关阅读:
    鸡尾酒之白兰地
    Hadoop面试总结(三)Hbase、Spark
    Hadoop面试总结(二)MySQL
    Hadoop面试总结(一)Linux命令、Scala
    View
    用户画像项目规划
    Apache kafka
    Resume
    蔡学镛
    【git】git常用操作
  • 原文地址:https://www.cnblogs.com/star5/p/1881919.html
Copyright © 2011-2022 走看看