用事务实现函数效果

 

 

--事務XML控制

 

 

-- 用事务/XML实现函数效果

 

create table ta( id int , name varchar ( 50))

insert ta

select 1, 'a' union all

select 1, 'b' union all

select 1, 'a' union all

select 2, 'e' union all

select 2, 'f' union all

select 3, 'g' union all

select 3, 'h' union all

select 3, 'i' union all

select 3, 'j' union all

select 4, 'k' union all

select 4, 'm' union all

select 4, 'l' union all

select 5, 'A' union all

select 5, 'B' union all

select 5, 'C' union all

select 5, 'D' union all

select 5, 'E' union all

select 6, 'F' union all

select 6, 'G' union all

select 6, 'H' union all

select 6, 'K' union all

select 6, 'M'

 

-- 合并效果

/*

ID          Name

----------- ----------

1           a ,b,a

2           e,f

3            g ,h,i,j

4           k,m,l

5           A ,B,C,D,E

6           F ,G,H,K,M

 

(6 個資料列受到影響 )

 

*/

 

-- 方法 1( 不用函数实现更新、查询 ) 如下用于几列合并一列方法 1 比方法 2 效率高

 

declare @tb table ( id int , name varchar ( 50), con int identity ( 1, 1))

insert @tb

select * from ta

 

begin tran

while exists( select 1 from @tb)

    begin

        update a

        set a. name= a. name+ ',' + b. name

        from ta a , @tb b

        where a. id= b. id  and

        not exists( select * from @tb where id= b. id  and con< b. con )

 

        delete b

        from @tb b where not exists( select 1 from @tb where id= b. id  and con< b. con)

    end

 

select distinct id, 显示 = stuff ( name , 1, charindex ( ',' , name ), '' ) from ta

 

-- 以下用于更新 commit tran 替换 rollback tran

--update ta set name=stuff(name,1,charindex(',',name),'')

--commit tran

 

rollback tran

 

select * from ta

 

 

-- 方法 2( 通过创建函数实现查询更新、查询 )

create function ta_fun( @id int )

returns varchar ( 1000)

as

begin

    declare @sql varchar ( 1000)

    set @sql= ''

    select @sql= @sql+ ',' + name from ta where id= @id

    --print @sql

    return stuff ( @sql, 1, 1, '' )

end

 

select distinct id, 显示 = dbo. ta_fun( id) from ta

--select id, 显示 =dbo.ta_fun(id) from ta group by id

-- 以下用函数更新

update ta set name = dbo. ta_fun( id)

 

--drop table ta 删测试表

--drop function ta_fun  删测试函数

 

-- 以下用 SQL2005 实现方法

 

--XML 方法 1

SELECT *

FROM ( SELECT DISTINCT id FROM ta ) A

OUTER APPLY

    ( SELECT [name]= STUFF ( REPLACE ( REPLACE (( SELECT name FROM ta N WHERE id = A. id FOR XML AUTO ), '<N name="' , ',' ), '"/>' , '' ), 1, 1, '' )) N

 

--XML 方法 2

select

    ID, [Name]= stuff (( select ',' + Name from Ta where ID= a. ID for xml path ( '' )), 1, 1, '' )

from Ta a

group by ID

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值