SQL连接字符串

时间:2016-02-09 12:16:28

标签: sql sql-server sql-server-2008

我在sql server 2008工作,我想连接两个字符串,条件是

@str1 = 'A1,B1,C1'
@str2 = 'A2,B2,C2'

我希望结果为

@result = 'A1,A2,B1,B2,C1,C2'

请帮忙......

4 个答案:

答案 0 :(得分:1)

首先创建一个拆分功能,以便单独获取项目:

CREATE FUNCTION [dbo].[Split]
(
    @String NVARCHAR(4000),
    @Delimiter NCHAR(1)
)
RETURNS TABLE
AS
RETURN
(
    WITH Split(stpos,endpos)
    AS(
        SELECT 0 AS stpos, CHARINDEX(@Delimiter,@String) AS endpos
        UNION ALL
        SELECT endpos+1, CHARINDEX(@Delimiter,@String,endpos+1)
            FROM Split
            WHERE endpos > 0
    )
    SELECT 'Id' = ROW_NUMBER() OVER (ORDER BY (SELECT 1)),
        'Data' = SUBSTRING(@String,stpos,COALESCE(NULLIF(endpos,0),LEN(@String)+1)-stpos)
    FROM Split
)
GO

现在您可以先拆分然后订购结果,然后连接值

DECLARE @DelimitedString NVARCHAR(128)
SET @DelimitedString =  @str1 + ',' + @str2
SELECT @result = COALESCE(@result + ',', '') +Data
  FROM (SELECT Data 
          FROM dbo.Split(@DelimitedString, ',')
      ORDER BY Data)

答案 1 :(得分:1)

存储数据的方式非常糟糕。但是,这是一个用于培训目的的解决方案:

DECLARE 
   @str1 varchar(30) = 'A1,B1,C1',
   @str2 varchar(30) = 'A2,B2,C2',
   @result varchar(60)

;WITH split as
(
  SELECT t.c.value('.', 'VARCHAR(2000)') x
  FROM (
      SELECT x = CAST('<t>' + 
          REPLACE(@str1 + ',' + @str2, ',', '</t><t>') + '</t>' AS XML)
  ) a
CROSS APPLY x.nodes('/t') t(c)
)
SELECT
  @result =
    STUFF(( 
        SELECT ',' + x
        FROM split
        ORDER BY x
        for xml path(''), type 
          ).value('.', 'varchar(max)'), 1, 1, '')

SELECT @result

结果:

A1,A2,B1,B2,C1,C2

答案 2 :(得分:0)

SET @result = @str1 + ',' + @str2
SELECT @result

更新1

我认为最好的方法是首先获取完整的字符串,然后用逗号分割它,然后将其存储在临时表中然后排序,这可能是一个好主意。

CREATE FUNCTION SplitString
(    
      @Input NVARCHAR(MAX),
      @Character CHAR(1)
)
RETURNS @Output TABLE (
      Item NVARCHAR(1000)
)
AS
BEGIN
      DECLARE @StartIndex INT, @EndIndex INT

      SET @StartIndex = 1
      IF SUBSTRING(@Input, LEN(@Input) - 1, LEN(@Input)) <> @Character
      BEGIN
            SET @Input = @Input + @Character
      END

      WHILE CHARINDEX(@Character, @Input) > 0
      BEGIN
            SET @EndIndex = CHARINDEX(@Character, @Input)

            INSERT INTO @Output(Item)
            SELECT SUBSTRING(@Input, @StartIndex, @EndIndex - 1)

            SET @Input = SUBSTRING(@Input, @EndIndex + 1, LEN(@Input))
      END

      RETURN
END
GO


SELECT Item FROM 
dbo.SplitString(@result,',') ORDER BY Item

答案 3 :(得分:0)

尝试:

SELECT stuff((SELECT ',' + T.str FROM
(SELECT 
    PARSENAME(REPLACE(@str1,',','.'),1) str UNION ALL
    PARSENAME(REPLACE(@str1,',','.'),2) str UNION ALL
    PARSENAME(REPLACE(@str1,',','.'),3) str UNION ALL
    PARSENAME(REPLACE(@str2,',','.'),1) str UNION ALL
    PARSENAME(REPLACE(@str2,',','.'),2) str UNION ALL
    PARSENAME(REPLACE(@str2,',','.'),3) str )T
    ORDER BY T.str
FOR XML PATH('')),1,1,'')