Parsing SQL Server 2005 overflow: Merging column values

Source: Internet
Author: User
Tags sql

Many people may find that there is no aggregate function for strings in SQL 2000, or in SQL 2005, so when we're dealing with the following requirements, it's a bit of a hassle, but in SQL Server 2005, this is an improvement that we can easily do.

问题描述:
无论是在sql 2000, 还是在 sql 2005 中,
都没有提供字符串的聚合函数, 所以, 当
我们在处理下列要求时,会比较麻烦:
有表tb, 如下:
id  value
----- ------
1   aa
1   bb
2   aaa
2   bbb
2   ccc
需要得到结果:
id   values
------ -----------
1   aa,bb
2   aaa,bbb,ccc
即, group by id, 求 value 的和(字符串相加)

1. The old solution

创建处理函数
CREATE FUNCTION dbo.f_str(@id int)
RETURNS varchar(8000)
AS
BEGIN
  DECLARE @r varchar(8000)
  SET @r = ''
  SELECT @r = @r + ',' + value
  FROM tb
  WHERE id=@id
  RETURN STUFF(@r, 1, 1, '')
END
GO
-- 调用函数
SELECt id, values=dbo.f_str(id)
FROM tb
GROUP BY id

2. New Solutions

示例数据
DECLARE @t TABLE(id int, value varchar(10))
INSERT @t SELECT 1, 'aa'
UNION ALL SELECT 1, 'bb'
UNION ALL SELECT 2, 'aaa'
UNION ALL SELECT 2, 'bbb'
UNION ALL SELECT 2, 'ccc'
-- 查询处理
SELECT *
FROM(
  SELECT DISTINCT
    id
  FROM @t
)A
OUTER APPLY(
  SELECT
    [values]= STUFF(REPLACE(REPLACE(
      (
        SELECT value FROM @t N
        WHERE id = A.id
        FOR XML AUTO
      ), '<N value="', ','), '"/>', ''), 1, 1, '')
)N/*--结果
id     values
----------- ----------------
1      aa,bb
2      aaa,bbb,ccc
(2 行受影响)
--*/

Note: The CLR for merging and splitting, sql2005 examples include:

After installing the example of SQL 2005, the default installation directory is Drive:program FilesMicrosoft SQL Server90samplesengineprogrammabilityclrstringutilities.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.