将长字符串分成多个字符串SQL

时间:2018-10-09 12:09:43

标签: sql sql-server

所以基本上,我希望将长字符串切成小块,但要保持单词完整。因此,如果我在JumpColumn栏中的FoxTable中有以下句子:

  

棕狐跳过了懒狗,然后懒狗跳过了棕狐

我想在SQL中将其拆分为最多20个字符(包括空格)。因此结果将是这样的:

the brown fox jumped 
 over the lazy dog
 and then the lazy 
dog jumped over the 
brown fox

但是请记住,JumpColumn列中有不同的句子,它们的长度和单词不同。

我的查询现在要做的是使用SQL Server中的SUBSTRING函数将其分成不同的行。

DECLARE @string_part1 NVARCHAR(500), 
        @string_part2 NVARCHAR(500), 
        @string_part3 NVARCHAR(500), 
        @string_part4 NVARCHAR(500),
        @string_part5 NVARCHAR(500),
        @LoopCount = 1

WHILE (@LoopCount <= 100)
BEGIN
     SELECT
      string_part1 NVARCHAR(500)  = SUBSTRING(JumpColumn, 0, 20)
     ,string_part2 NVARCHAR(500)  = SUBSTRING(JumpColumn, 20, 20)
     ,string_part3 NVARCHAR(500)  = SUBSTRING(JumpColumn, 40, 20)
     ,string_part4 NVARCHAR(500)  = SUBSTRING(JumpColumn, 60, 20)
     ,string_part5 NVARCHAR(500)  = SUBSTRING(JumpColumn, 80, 20)

FROM FoxTable
WHERE Row = @LoopCount

SET @LoopCount = @LoopCount + 1
END

2 个答案:

答案 0 :(得分:0)

这将起作用

Expression<Func<T, bool>> predicate

我知道不是很整洁,但是可以完成工作。

答案 1 :(得分:0)

从SQL Server 2016开始,您可以使用string_split将句子拆分为单词(在SQL Server 2016之前,您可以使用可以在网上找到的类似功能):

declare @string         nvarchar(max) = 'the brown fox jumped over the lazy dog and then the lazy dog jumped over the brown fox'
declare @tmp            table (row_num int identity(1,1), word nvarchar(20), word_length int)
declare @total          int  
declare @counter        int = 1 
declare @current_lenght int = 0
declare @current_string nvarchar(20) = '' 
declare @next_string    nvarchar(20) = ''
declare @res            table (words nvarchar(20))

insert into @tmp
select value, len(value) 
from string_split(@string, ' ')

select @total = count(*) from @tmp

while @counter <= @total
    begin
        select @next_string = word 
        from @tmp
        where row_num = @counter

        if len(case when @counter = 1 then '' else @current_string + ' ' end + @next_string) > 20
            begin
                insert into @res values (@current_string)
                set @current_string = @next_string
            end
        else
            set @current_string = case when @counter = 1 then '' else @current_string + ' ' end + @next_string
        set @counter = @counter + 1
    end
insert into @res values (@current_string)

select * from @res

结果:

enter image description here