在MS SQL中拆分单词

时间:2017-08-07 19:48:40

标签: sql sql-server tsql

我已经创建了一种在MS SQL中获取字符串并在空格中分解以避免单词拆分的方法。如果每行为17个字符或更大,则将字符串拆分为3个单独的字符串以用于新行。

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 个答案:

答案 0 :(得分: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