還有另一個選擇:
使用在演唱會幾乎所有的解析/分割函數CROSS APPLY將會做
例
Declare @YourTable table (ID int,SomeCol varchar(500))
Insert Into @YourTable values
(1,'ABB_FET_abb_98693989-121966_20170304052411709.csv')
,(2,'XXX_YYY_zzz_12345678-123456_20170304052411709.csv')
Select A.ID
,[ERP ID] = left(B.RetVal,charindex('-',B.RetVal)-1)
,[CATALOG ID] = B.RetVal
From @YourTable A
Cross Apply (Select * from [dbo].[udf-Str-Parse-8K](A.SomeCol,'_') Where RetVal like '%-%') B
返回
ID ERP ID CATALOG ID
1 98693989 98693989-121966
2 12345678 12345678-123456
分析函數,如果有興趣的二手
CREATE FUNCTION [dbo].[udf-Str-Parse-8K] (@String varchar(max),@Delimiter varchar(25))
Returns Table
As
Return (
with cte1(N) As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
cte2(N) As (Select Top (IsNull(DataLength(@String),0)) Row_Number() over (Order By (Select NULL)) From (Select N=1 From cte1 a,cte1 b,cte1 c,cte1 d) A),
cte3(N) As (Select 1 Union All Select t.N+DataLength(@Delimiter) From cte2 t Where Substring(@String,t.N,DataLength(@Delimiter)) = @Delimiter),
cte4(N,L) As (Select S.N,IsNull(NullIf(CharIndex(@Delimiter,@String,s.N),0)-S.N,8000) From cte3 S)
Select RetSeq = Row_Number() over (Order By A.N)
,RetVal = LTrim(RTrim(Substring(@String, A.N, A.L)))
From cte4 A
);
--Orginal Source http://www.sqlservercentral.com/articles/Tally+Table/72993/
--Select * from [dbo].[udf-Str-Parse-8K]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse-8K]('John||Cappelletti||was||here','||')
[SQL Server的正則表達式(HTTPS的可能重複://計算器。 COM /問題/ 5212665/SQL服務器正則表達式) –