我有一個表,如下字符串轉換爲逗號分隔值
DECLARE @T TABLE(Data VARCHAR(MAX))
INSERT INTO @T
SELECT 'SQL' UNION ALL SELECT 'JOB'
需要如下的輸出,但不使用任何UDF。
Data String
------------
SQL S,Q,L
JOB J,O,B
請幫我在這
我有一個表,如下字符串轉換爲逗號分隔值
DECLARE @T TABLE(Data VARCHAR(MAX))
INSERT INTO @T
SELECT 'SQL' UNION ALL SELECT 'JOB'
需要如下的輸出,但不使用任何UDF。
Data String
------------
SQL S,Q,L
JOB J,O,B
請幫我在這
當然,你可以:)。你可以使它更短...
DECLARE @T TABLE(Data VARCHAR(MAX))
INSERT INTO @T
SELECT 'SQL' UNION ALL SELECT 'JOB';
With cte as
(
Select Data, Len(Data) DataLength, 1 level
From @t
Union All
Select Data, DataLength - 1, level + 1
From cte
Where DataLength > 1
),
cte2 as
(
Select Data, SUBSTRING(Data, DataLength, 1) DataLetter, level
From cte
),
cte3 as
(
Select Data,
(
SELECT DataLetter + ','
FROM cte2 c
Where c.Data = cte2.Data
Order By level desc
FOR XML PATH(''), TYPE
).value('.[1]', 'NVARCHAR(1000)') DataComa
From cte2
Group By Data
)
Select Data, substring(DataComa, 1, Len(DataComa) - 1) Data2
From cte3
這是很容易做的UDF。 但是,如果你想出來UDF,我能想到的只有一個辦法是
像這樣
DECLARE @T TABLE(Data VARCHAR(MAX))
INSERT INTO @T
SELECT 'SQL' UNION ALL SELECT 'JOB'
select replace(replace(replace(data,'S','S,'),'Q','Q,'),'L','L,') from @T
在這裏你必須更換所有的26個字符與替換功能。即, 'A' 與 'A', 'B' 與 'B' .... '' 與 'Z Z,'
使用I用於INITCAP函數這裏http://beyondrelational.com/modules/2/blogs/70/posts/10901/tsql-initcap-function-convert-a-string-to-proper-case.aspx
DECLARE @T TABLE(Data VARCHAR(MAX))
INSERT INTO @T
SELECT 'SQL' UNION ALL SELECT 'JOB'
select data,
upper(replace(replace(replace(replace(replace(replace(replace(
replace(replace(replace(replace(replace(replace(replace(
replace(replace(replace(replace(replace(replace(replace(
replace(replace(replace(replace(replace(
' '+data ,
' a','a,'),' b','b,'),'c','c,'),'d','d,'),'e','e,'),'f','f,'),
' g','g,'),' h','h,'),'i','i,'),'j','j,'),'k','k,'),'l','l,'),
' m','m,'),' n','n,'),'o','o,'),'p','p,'),'q','q,'),'r','r,'),
' s','s,'),' t','t,'),'u','u,'),'v','v,'),'w','w,'),'x','x,'),
' y','y,'),' z','z,')) as splitted_data
from
@t
相同的方法
遲到了,但這裏有一個稍短的版本:
DECLARE @T TABLE(Data VARCHAR(MAX));
INSERT INTO @T VALUES('SQL'),('JOB'),('FLOOB');
;WITH n AS (SELECT TOP (SELECT MAX(LEN(Data)) FROM @T)
n = ROW_NUMBER() OVER (ORDER BY [object_id]) FROM sys.all_objects
),
t AS (SELECT n, Data, Letter = SUBSTRING(t.Data, n.n, 1) FROM n
INNER JOIN @T AS t ON SUBSTRING(t.Data, n.n, 1) > ''
)
SELECT Data, STUFF((SELECT ',' + letter FROM t AS t2
WHERE t2.Data = t.Data ORDER BY t2.n FOR XML PATH(''),
TYPE).value('.[1]', 'varchar(max)'), 1, 1, '')
FROM t GROUP BY Data;
結果:
FLOOB F,L,O,O,B
JOB J,O,B
SQL S,Q,L
創建標量值的函數,它接受的字符串和用','返回字符串 – 2012-07-17 11:37:08
我需要它而不使用任何用戶定義函數 – sganesh 2012-07-17 11:39:36
你能解釋爲什麼它不能用函數完成嗎? – 2012-07-17 12:06:36