zoukankan      html  css  js  c++  java
  • sql基础操作之字符串拼接


    又一篇笔记,以备后用!!

         需求:

    有表tb,表有两个字段,分别为:id,value。

    表中存有数据如下:id        value

                             1         a

                             1         a1

                             1         a2

                             2         b

                             2         b1

                             3         c1

                             3         c2

         需要通过查询实现:1         a,a1,a2

                                  2         b,b1

                                  3         c1,c2

    实现方法:

              1、sql2000 使用合并函数:

              create function f_tb(@id int)
    returns varchar(8000)
    as
    begin
     
    declare @str varchar(8000)
     
    set @str = ''
     
    select @str = @str + ',' + cast(value as varchar) from tb where id = @id
     
    set @str = right(@str , len(@str) - 1)
     
    return(@str)
    End
    go

    --调用自定义函数得到结果:
    select distinct id ,dbo.f_tb(id) as value from t

              2、sql2005 处理方式如下:

    SELECT * FROM(SELECT DISTINCT id FROM tb)A OUTER APPLY(
           
    SELECT [values]= STUFF(REPLACE(REPLACE(
                (
                   
    SELECT value FROM tb N
                   
    WHERE id = A.id
                   
    FOR XML AUTO
                ),
    '<N value="', ','), '"/>', ''), 1, 1, '')
    )N

    参考: http://topic.csdn.net/u/20080410/15/88f6491b-d9fe-4bd1-a350-22b4d5c9d415.html   
  • 相关阅读:
    「Poetize10」封印一击
    「Poetize10」能量获取
    vijosP1499炸毁燃料库
    BZOJ3550: [ONTAK2010]Vacation
    总结#3--一类最小割问题
    BZOJ1976: [BeiJing2010组队]能量魔方 Cube
    BZOJ2132: 圈地计划
    BZOJ2127: happiness
    BZOJ1754: [Usaco2005 qua]Bull Math
    920. 会议室
  • 原文地址:https://www.cnblogs.com/hanmos/p/1997036.html
Copyright © 2011-2022 走看看