IM在SQL Server 2008中的工作,我想連接兩個字符串,條件是SQL連接字符串
@str1 = 'A1,B1,C1'
@str2 = 'A2,B2,C2'
我想要的結果作爲
@result = 'A1,A2,B1,B2,C1,C2'
請幫助...
IM在SQL Server 2008中的工作,我想連接兩個字符串,條件是SQL連接字符串
@str1 = 'A1,B1,C1'
@str2 = 'A2,B2,C2'
我想要的結果作爲
@result = 'A1,A2,B1,B2,C1,C2'
請幫助...
您存儲數據的方式是非常糟糕的做法。不過這裏是訓練目的的解決方案:
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
首先創建一個拆分功能來讓你的項目分開:
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
現在你可以先拆分再和訂購您的結果,然後CONCAT值
DECLARE @DelimitedString NVARCHAR(128)
SET @DelimitedString = @str1 + ',' + @str2
SELECT @result = COALESCE(@result + ',', '') +Data
FROM (SELECT Data
FROM dbo.Split(@DelimitedString, ',')
ORDER BY Data)
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
我想要這種格式'A1,A2,B1,B2,C1,C2' – user2695128
@ user2695128請檢查我的更新 – Hemal
嘗試:
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,'')
非常感謝你.....這工作正常 – user2695128
@ user2695128:歡迎,如果它是爲你工作,你可以把它標記爲答案 –
'設置@result = @ STR1 + '' + @ str2' –
我想要'A1,A2,B1,B2,C1,C2'...與你的答案一樣,將會產生像'A1,B1,C1,A2,B2,C2' – user2695128
你必須使用splitter功能來做到這一點。 Google s * ql服務器拆分字符串* –