如果您對UDF開放。
分解和提取字符串的分層(charindex,左,右,...),我修改了一個分析/分割udf來接受兩個不相似的參數。
現在,解析地址可能是一個滑坡。見我的答案在這裏Address standardization within a database
例
Declare @YourTable table (Address1 varchar(450))
Insert into @YourTable values
('Apt. 2B 123 Fake Street')
,('123 Main St. Apt. 1A')
,('100 North Main St.')
Select A.Address1
,Apt = 'Apt. '+B.RetVal
From @YourTable A
Outer Apply [dbo].[udf-Str-Extract](' '+A.Address1+' ',' Apt. ',' ') B
返回
Address1 Apt
Apt. 2B 123 Fake Street Apt. 2B
123 Main St. Apt. 1A Apt. 1A
100 North Main St. NULL
的UDF如果有興趣
CREATE FUNCTION [dbo].[udf-Str-Extract] (@String varchar(max),@Delimiter1 varchar(100),@Delimiter2 varchar(100))
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 N1,cte1 N2,cte1 N3,cte1 N4,cte1 N5,cte1 N6) A),
cte3(N) As (Select 1 Union All Select t.N+DataLength(@Delimiter1) From cte2 t Where Substring(@String,t.N,DataLength(@Delimiter1)) = @Delimiter1),
cte4(N,L) As (Select S.N,IsNull(NullIf(CharIndex(@Delimiter1,@String,s.N),0)-S.N,8000) From cte3 S)
Select RetSeq = Row_Number() over (Order By N)
,RetPos = N
,RetVal = left(RetVal,charindex(@Delimiter2,RetVal)-1)
From (
Select *,RetVal = Substring(@String, N, L)
From cte4
) A
Where charindex(@Delimiter2,RetVal)>1
)
/*
Max Length of String 1MM characters
Declare @String varchar(max) = 'Dear [[FirstName]] [[LastName]], ...'
Select * From [dbo].[udf-Str-Extract] (@String,'[[',']]')
*/
在TSQL中解析地址似乎不是一個好主意。 –