你需要的是一個分離的用戶定義函數。就這樣,該解決方案看起來像
With SplitValues As
(
Select T.Name, Z.Position, Z.Value
, Row_Number() Over (Partition By T.Name Order By Z.Position) As Num
From Table As T
Cross Apply dbo.udf_Split(T.Name, ' ') As Z
)
Select Name
, FirstName.Value
, Case When ThirdName Is Null Then SecondName Else ThirdName End As LastName
From SplitValues As FirstName
Left Join SplitValues As SecondName
On S2.Name = S1.Name
And S2.Num = 2
Left Join SplitValues As ThirdName
On S2.Name = S1.Name
And S2.Num = 3
Where FirstName.Num = 1
這裏是一個樣本分割功能:
Create Function [dbo].[udf_Split]
(
@DelimitedList nvarchar(max)
, @Delimiter nvarchar(2) = ','
)
RETURNS TABLE
AS
RETURN
(
With CorrectedList As
(
Select Case When Left(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
+ @DelimitedList
+ Case When Right(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
As List
, Len(@Delimiter) As DelimiterLen
)
, Numbers As
(
Select TOP(Coalesce(DataLength(@DelimitedList)/2,0)) Row_Number() Over (Order By c1.object_id) As Value
From sys.columns As c1
Cross Join sys.columns As c2
)
Select CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen As Position
, Substring (
CL.List
, CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen
, CharIndex(@Delimiter, CL.list, N.Value + 1)
- (CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen)
) As Value
From CorrectedList As CL
Cross Join Numbers As N
Where N.Value <= DataLength(CL.List)/2
And Substring(CL.List, N.Value, CL.DelimiterLen) = @Delimiter
)
這是你想在SQL Server中做的事嗎?在一個'SELECT'語句中?在INSERT或UPDATE語句中?更多細節可以幫助我們回答你的問題 – BinaryTox1n 2011-02-25 22:58:07
這是名字存儲的糟糕設計,你應該考慮把第一個,最後一個,中間名作爲單獨的列,我希望你不要在這個表中做任何報告,按照你的要求拆分名字 – 2011-02-25 22:58:59
需要在選擇語句中。其實它是存儲過程,它是通過從表中選擇值插入數據。所以我得到它在選擇語句,將是偉大的... – Shahsra 2011-02-25 23:00:37