本文介紹了tsql 函數拆分字符串的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我想知道是否有人可以幫助我.
I wonder if anyone can help me.
我需要一個 tsql 函數來分割給定的值,例如:
I need a tsql function to split a given value such as:
1) 00 Not specified
3) 01-05 Global WM&BB | Operations
2) 02-05-01 Global WM&BB | Operations | Operations n/a
我需要得到這樣的結果:
I need to get a result like this:
cat1 cat1descr cat2 cat2descr cat3 cat3descr
----------------------------------------------------------------
00 Not especified null null null null
01 Global WM&BB 05 Operations null null
01 Global WM&BB 05 Operations 01 Operations n/a
結果將始終有 6 列
select funcX('00 未指定');
select funcX('00 Not specified');
cat1 cat1descr cat2 cat2descr cat3 cat3descr
----------------------------------------------------------------
00 Not especified null null null null
推薦答案
這將適用于 SQL Server 2005 和 SQL Server 2008.我假設您的第一個數字序列固定為 1、2、或 3. 您可以使用較少的級聯 CTE 來完成此操作,但我發現 SUBSTRING/CHARINDEX/LEN 語法很快就會變得非常難以閱讀和調試.
This will work on SQL Server 2005 and SQL Server 2008. I have assumed that your first sequence of digits is fixed to 2-digit groups of 1, 2, or 3. You can do this with fewer cascading CTEs but I find the SUBSTRING/CHARINDEX/LEN syntax can quickly become very difficult to read and debug.
DECLARE @foo TABLE
(
bar VARCHAR(4000)
);
INSERT @foo(bar) SELECT '00 Not specified'
UNION ALL SELECT '01-05 Global WM&BB | Operations'
UNION ALL SELECT '02-05-01 Global WM&BB | Operations | Operations n/a';
WITH split1 AS
(
SELECT
n = SUBSTRING(bar, 1, CHARINDEX(' ', bar)-1),
w = SUBSTRING(bar, CHARINDEX(' ', bar)+1, LEN(bar)),
rn = ROW_NUMBER() OVER (ORDER BY bar)
FROM
@foo
),
split2 AS
(
SELECT
rn,
cat1 = LEFT(n, 2),
wl = RTRIM(SUBSTRING(w, 1,
COALESCE(NULLIF(CHARINDEX('|', w), 0)-1, LEN(w)))),
wr = LTRIM(SUBSTRING(w, NULLIF(CHARINDEX('|', w),0) + 1, LEN(w))),
cat2 = NULLIF(SUBSTRING(n, 4, 2), ''),
cat3 = NULLIF(SUBSTRING(n, 7, 2), '')
FROM
split1
),
split3 AS
(
SELECT
rn,
cat1descr = wl,
cat2descr = RTRIM(SUBSTRING(wr, 1,
COALESCE(NULLIF(CHARINDEX('|', wr), 0)-1, LEN(wr)))),
cat3descr = LTRIM(SUBSTRING(wr,
NULLIF(CHARINDEX('|', wr),0) + 1, LEN(wr)))
FROM
split2
)
SELECT
s2.cat1, s3.cat1descr,
s2.cat2, s3.cat2descr,
s2.cat3, s3.cat3descr
FROM split2 AS s2
INNER JOIN split3 AS s3
ON s2.rn = s3.rn;
這篇關于tsql 函數拆分字符串的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!