2017-08-07 44 views
0

我已經創建了一種方法來在MS SQL中取出一個字符串並將其分解到一個空格處以避免分詞。如果每行的長度等於或大於17個字符,則會將字符串拆分爲3個單獨的字符串作爲新行。在MS SQL中拆分單詞

DECLARE @Prod_Desc varchar(50) = '12345 BAG 15 LB NR SML BTS CHICKEN MEAL AND RICE' 
DECLARE @Prod_Desc_Line2 varchar(50); 
DECLARE @Prod_Desc_Line3 varchar(50); 

-- Generate second line and center 
IF len(@Prod_Desc) >= 17 
BEGIN 
SELECT @Prod_Desc_Line2 = SUBSTRING(@Prod_Desc, 18 - CHARINDEX(' ', REVERSE(SUBSTRING(@Prod_Desc, 1, 17)), 1), len(@Prod_Desc) + CHARINDEX(' ', REVERSE(SUBSTRING(@Prod_Desc, 1, 17)), 1) - 17); 
SELECT @Prod_Desc = SUBSTRING(@Prod_Desc, 1, 17 - CHARINDEX(' ', REVERSE(SUBSTRING(@Prod_Desc, 1, 17)), 1)); 
END; 

-- Generate third line and center 
IF len(@Prod_Desc_Line2) >= 17 
BEGIN 
SELECT @Prod_Desc_Line3 = SUBSTRING(@Prod_Desc_Line2, 18 - CHARINDEX(' ', REVERSE(SUBSTRING(@Prod_Desc_Line2, 1, 17)), 1), len(@Prod_Desc_Line2) + CHARINDEX(' ', REVERSE(SUBSTRING(@Prod_Desc_Line2, 1, 17)), 1) - 17); 
SELECT @Prod_Desc_Line2 = SUBSTRING(@Prod_Desc_Line2, 1, 17 - CHARINDEX(' ', REVERSE(SUBSTRING(@Prod_Desc_Line2, 1, 17)), 1)); 
END; 

PRINT(@Prod_Desc); 
PRINT(@Prod_Desc_Line2); 
PRINT(@Prod_Desc_Line3); 

輸出:

12345 BAG 15 LB 
NR SML BTS 
CHICKEN MEAL AND RICE 

它的工作原理我怎麼想,但我認爲它看起來馬虎。我想知道是否有更好的方法來做這個字符串的劃分,或者如果有一個函數存在這樣做?

爲了便於說明,如果一個字符串大於17個字符,它會在限制命中之前找到最後一個空格,將其從原始字符串中截斷,並將其添加到下一行的下一個字符串中。

+1

這將能更好地貼在代碼審查。 https://codereview.stackexchange.com/ –

+0

還有很多其他的方法來做到這一點 - 這個問題是廣泛的方式stackoverflow – Hogan

+0

當最後一行是7500個字符會發生什麼?你想要它超長?另外,你是否試圖將其應用於一組數據?如果是這樣,那麼我猜你有一個基於你當前邏輯的循環。這是真的? – scsimon

回答

2

一種選擇

DECLARE @S varchar(100) = '12345 BAG 15 LB NR SML BTS CHICKEN MEAL AND RICE' 
Declare @MaxLen int = 17 

Select Line1 
     ,Line2 = ltrim(stuff(Line2,1,len(Line1),'')) 
     ,Line3 = ltrim(stuff(Line3,1,len(Line2),'')) 
From (
     Select Line1 = Left(@S,@MaxLen-CharIndex(' ',Reverse(Left(@S,@MaxLen)))) 
       ,Line2 = Left(@S,@MaxLen*2-CharIndex(' ',Reverse(Left(@S,@MaxLen*2)))) 
       ,Line3 = @S 
    ) A 

返回

Line1    Line2  Line3 
12345 BAG 15 LB NR SML BTS CHICKEN MEAL AND RICE 

編輯集理論

Declare @YourTable table (ID int,SomeCol varchar(max)) 
Insert Into @YourTable values 
(1,'12345 BAG 15 LB NR SML BTS CHICKEN MEAL AND RICE') 
,(2,'Some Random Text should be split into 3 strings') 

Declare @MaxLen int = 18 --<< Changed to 18 

    Select A.ID 
      ,Line1 
      ,Line2 = ltrim(stuff(Line2,1,len(Line1),'')) 
      ,Line3 = ltrim(stuff(Line3,1,len(Line2),'')) 
    From @YourTable A 
    Cross Apply (
        Select Line1 = Left(SomeCol,@MaxLen-CharIndex(' ',Reverse(Left(SomeCol,@MaxLen)))) 
          ,Line2 = Left(SomeCol,@MaxLen*2-CharIndex(' ',Reverse(Left(SomeCol,@MaxLen*2)))) 
          ,Line3 = SomeCol 
       ) B  

返回

ID Line1    Line2     Line3 
1 12345 BAG 15 LB  NR SML BTS CHICKEN  MEAL AND RICE 
2 Some Random Text should be split  into 3 strings 
+0

1,因爲它可以適用於廣泛的應用,我不認爲* OP邏輯會。 – scsimon