2014-01-29 67 views
0

我目前正在使用函數拆分以分號分隔的字符串。該功能無法分割長度爲12 000個字符的字符串。它運行幾分鐘,然後SSMS凍結。T-SQL - 拆分字符串函數

你能否給我建議我的功能,這是能夠處理這個?我會盡快發佈我使用PC的功能。

謝謝。

功能(現在按預期工作):

/* fce SplitList start */ 
Declare @CommaDelimitedFieldNames Varchar(MAX) 
Declare @CharToFind VarChar(10) 
Set @CommaDelimitedFieldNames = REPLACE(@String,' ','') 
Set @CharToFind = ';' 

Declare @Tbl_FieldNames Table 
(
Position Integer Identity(1,1), 
FieldName VarChar(8000) 
) 

Set @CommaDelimitedFieldNames = @CommaDelimitedFieldNames + @CharToFind 
Declare @Pos1 Int 
Declare @pos2 Int 

Set @Pos1=1 
Set @Pos2=1 

While @Pos1<DataLength(@CommaDelimitedFieldNames) 
Begin 
Set @Pos1 = CharIndex(@CharToFind, @CommaDelimitedFieldNames,@Pos1) 
Insert @Tbl_FieldNames Select Cast(Substring(@CommaDelimitedFieldNames,@Pos2,@[email protected]) As NVARCHAR(MAX)) 
Set @[email protected]+1 
Set @Pos1 = @Pos1+1 
End 
/* fce Splitlist end */ 
+0

Sql Server對可存儲在varchar(字符串數據類型)中的字符數有限制。 在嘗試使用TSQL之前,您必須檢查您的CSV字符串的長度。 http://stackoverflow.com/questions/7611394/maximum-size-of-a-varcharmax-variable – DhruvJoshi

+0

謝謝你的回答。我使用NVARCHAR(MAX)來聲明變量。它返回整個字符串 - 不會丟失字符。我將發佈我使用的功能。問題必須在函數本身。 – Rutz

+0

你怎麼分裂?它可能是你使用的函數,它只支持varchar(4000)或其他東西。關於脫口而言 - 在數據庫中拆分這樣的字符串看起來像使它工作,它不應該這樣做:) –

回答

0

感謝您對您的建議。問題出在功能本身。我應該使用varchar(max)而不是nvachar(max)作爲變量@CommaDelimitedFieldNames(現在已更正)。分割12 000個字符的字符串現在需要大約3秒鐘。