0

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

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

3 回答 3

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)
于 2013-09-26T09:26:54.837 回答
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)
于 2013-09-26T09:36:50.583 回答
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
于 2013-10-01T11:39:46.067 回答