与空间分裂一个长词

时间:2013-09-26 09:01:32

标签: sql-server-2008 split

我有一个很长的字符串。我想在整个字符串中检查连续15个字母,如果没有空格我必须手动在sql server中放置一个空格。任何人都可以帮忙吗?

For eg. my string is 'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ'
then it should appear like 'ABCDEFGHIJKLMNOP QRSTUVWXYZABCDE FGHIJKLMNOPQRST UVWXYZ'

3 个答案:

答案 0 :(得分:1)

我不知道如何在单个语句中执行此操作,但您可以创建类似这样的sql函数

create function AddStuffCharacterInLength (@original nvarchar(100), @take int, @stuff varchar(100))
returns nvarchar(200)
AS
BEGIN
    declare @result nvarchar(200)
declare @len int
declare @skip int

set @len = len(@original)
set @result = ''
set @skip = (@take * -1) + 1

    while @len > 0
    begin
        set @result = @result + substring(@original, @skip + @take, @take)
        set @len = @len - @take
        set @skip = @skip + @take
        if @len > 0
            set @result = @result + ' '
    end

    RETURN @result 
END

并像这样使用

select dbo.AddStuffCharacterInLength ('ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ',15, ' ')

输出应为

----------------------------------------------------------------------------------------------------
ABCDEFGHIJKLMNO PQRSTUVWXYZABCD EFGHIJKLMNOPQRS TUVWXYZ

(1 row(s) affected)

答案 1 :(得分:1)

你可以使用像这样的函数

IF EXISTS(SELECT * FROM sysobjects WHERE ID = OBJECT_ID('UF_StringSplitter'))
 DROP FUNCTION UF_StringSplitter
GO

CREATE FUNCTION UF_StringSplitter
(
 @psCSString VARCHAR(MAX)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
 DECLARE @sTemp VARCHAR(MAX)
 DECLARE @tTemp VARCHAR(MAX)
 SET @tTemp=''

 WHILE LEN(@psCSString)>15
 BEGIN
  SET @sTemp = LEFT(@psCSString, 15)
  SET @psCSString = SUBSTRING(@psCSString,16, LEN(@psCSString))

  IF @psCSString LIKE ' %'
     SET @tTemp=@tTemp+@sTemp   
  ELSE      
     SET @tTemp=@tTemp+@sTemp+' '      
 END
 SET @tTemp=@tTemp+@psCSString
RETURN @tTemp
END
Go

这里我对分割值进行了硬编码,你可以使用函数

UPDATE mytable SET mycol=dbo.UF_StringSplitter(mycol)

答案 2 :(得分:1)

@ dcp1986:我试过你的功能如下。

SELECT dbo.UF_StringSplitter('HeloEveryonehru Howslyfgoingonn HaveaGoodDayGoodMorning')

但意外的分裂发生了。我认为你的功能必须修改如下,以获得正确的结果:

IF EXISTS(SELECT * FROM sysobjects WHERE ID = OBJECT_ID('UF_StringSplitter'))
    DROP FUNCTION UF_StringSplitter
GO

CREATE FUNCTION UF_StringSplitter (
 @psCSString VARCHAR(MAX)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
 DECLARE @sTemp VARCHAR(MAX)
 DECLARE @tTemp VARCHAR(MAX)
 SET @tTemp=''

 WHILE LEN(@psCSString)>15
 BEGIN
  SET @sTemp = LEFT(LTRIM(@psCSString), 15)
  SET @psCSString = LTRIM(SUBSTRING(@psCSString,16, LEN(@psCSString)))

  IF @psCSString LIKE ' %'
     SET @tTemp=@tTemp+@sTemp   
  ELSE      
     SET @tTemp=@tTemp+@sTemp+' '      
 END
 SET @tTemp=@tTemp+@psCSString
RETURN @tTemp
END