1

您如何在大写字母出现或真正需要空格的字符串中添加空格。

示例代码是:

DECLARE @teams TABLE (Team NVARCHAR(100))

INSERT INTO @teams
SELECT 'TataConsultencyServices'
UNION ALL
SELECT 'TataConsultencyCompany'
UNION ALL
SELECT 'CompanyHumanResource'

预期结果

Tata Consultency Services
Tata Consultency Company
Company Human Resource
4

3 回答 3

0

您肯定会从中得到一些帮助 -

CREATE FUNCTION CaseSensitiveSQLSplitFunction
(
 @str nvarchar(max)
)
returns @t table (val nvarchar(max))
as
begin

declare @i int, @j int
select @i = 1, @j = len(@str)

declare @w nvarchar(max)

while @i <= @j
begin
 if substring(@str,@i,1) = UPPER(substring(@str,@i,1)) collate Latin1_General_CS_AS
 begin
  if @w is not null
   insert into @t (val) select @w
  set @w = substring(@str,@i,1)
 end
 else
  set @w = @w + substring(@str,@i,1)
 set @i = @i + 1
end
if @w is not null
 insert into @t (val) select @w

return

end

以样本为:-

declare @str nvarchar(max) = N'ThisIsATest'
select * from dbo.CaseSensitiveSQLSplitFunction(@str)
set @str = N'ThisIsASqlServerCaseSensitiveSplitStringFunction'
select * from dbo.CaseSensitiveSQLSplitFunction(@str)

在此处输入图像描述

现在可以以从行到单列值的方式对字符串值进行 sql 连接。我们可以使用任何 sql 连接函数。

declare @str nvarchar(max) = N'ThisIsATest'
SELECT LTRIM(STUFF((
  SELECT ' ' + val FROM dbo.CaseSensitiveSQLSplitFunction(@str) FOR XML PATH('')
  ), 1, 1, '')) string

set @str = N'ThisIsASqlServerCaseSensitiveSplitStringFunction'
SELECT LTRIM(STUFF((
  SELECT ' ' + val FROM dbo.CaseSensitiveSQLSplitFunction(@str) FOR XML PATH('')
  ), 1, 1, '')) string

在此处输入图像描述

于 2013-09-16T16:19:39.527 回答
0

基于集合的解决方案:

DECLARE @s NVARCHAR(100);
SET @s = 'CompanyHumanResources';

DECLARE @Idx INT = 1;
WITH CteRecursive
AS
(
    SELECT  1 AS Idx, 
            CONVERT(NVARCHAR(200), @s) AS String
    UNION ALL
    SELECT  src.Idx + src.IsUpper + 1,
            CONVERT(NVARCHAR(200),
                CASE WHEN src.IsUpper = 1 THEN STUFF(src.String, src.Idx+1, 0, ' ') ELSE src.String END
            )
    FROM
    (
        SELECT  rec.*,
                CASE WHEN SUBSTRING(rec.String, rec.Idx, 1) <> ' ' AND SUBSTRING(rec.String, rec.Idx+1, 1) LIKE '[A-Z]' AND SUBSTRING(rec.String, rec.Idx+1, 1) COLLATE Romanian_CS_AS = UPPER(SUBSTRING(rec.String, rec.Idx+1, 1)) COLLATE Romanian_CS_AS THEN 1 ELSE 0 END AS IsUpper
        FROM    CteRecursive rec
        WHERE   rec.Idx + 1 <= LEN(rec.String)
    ) src
)
SELECT  TOP(1) x.String
FROM    CteRecursive x
ORDER BY x.Idx DESC;

结果:

String
-----------------------
Company Human Resources
于 2013-09-16T19:26:11.700 回答
0

WHILE 1 = 1 BEGIN UPDATE @teams SET TeamName = STUFF(TeamName, patindex('%[az,.][AZ]%', TeamName COLLATE Latin1_General_BIN) + 1,0,' ') WHERE patindex('%[az, .][AZ]%', TeamName COLLATE Latin1_General_BIN) > 0

          IF @@ROWCOUNT = 0 BREAK

结尾

UPDATE @teams SET TeamName = STUFF(TeamName, patindex('%[AZ][az]%', RIGHT(TeamName,LEN(TeamName) -1) COLLATE Latin1_General_BIN) +1 ,0,' ') WHERE patindex('% [AZ][az]%', TeamName COLLATE Latin1_General_BIN) > 0

于 2013-09-23T11:57:33.830 回答