找到大写字符然后添加空格

时间:2013-05-10 02:09:49

标签: sql uppercase

我买了一个SQL World City / State数据库。在状态数据库中,它将状态名称压在一起。例如:“NorthCarolina”,或“SouthCarolina”......

在SQL中有一种方法可以循环并找到大写字符并添加空格???

这样“NorthCarolina”成为“北卡罗莱纳州”???

3 个答案:

答案 0 :(得分:7)

创建此功能

if object_id('dbo.SpaceBeforeCaps') is not null
    drop function dbo.SpaceBeforeCaps
GO
create function dbo.SpaceBeforeCaps(@s varchar(100)) returns varchar(100)
as
begin
    declare @return varchar(100);
    set @return = left(@s,1);
    declare @i int;
    set @i = 2;
    while @i <= len(@s)
    begin
        if ASCII(substring(@s,@i,1)) between ASCII('A') and ASCII('Z')
            set @return = @return + ' ' + substring(@s,@i,1)
        else
            set @return = @return + substring(@s,@i,1)
        set @i = @i + 1;
    end;
    return @return;
end;
GO

然后您可以使用它来更新数据库

update tbl set statename = select dbo.SpaceBeforeCaps(statename);

答案 1 :(得分:0)

有几种方法可以解决这个问题

  1. 使用模式和PATINDEX feature构建函数。

  2. 为每个案例链接最小REPLACE语句(例如REPLACE(state_name, 'hC', 'h C' for your example case)。这似乎是一种黑客行为,但实际上可能会给你最好的表现,因为你有这么小的一套替代品。

答案 2 :(得分:0)

如果你绝对不能创建函数并将其作为一次性需要,你可以使用递归CTE打破字符串(并在需要的同时添加空格),然后使用FOR XML重新组合字符。下面举例说明:

-- some sample data
create table #tmp (id int identity primary key, statename varchar(100));
insert #tmp select 'NorthCarolina';
insert #tmp select 'SouthCarolina';
insert #tmp select 'NewSouthWales';

-- the complex query updating the "statename" column in the "#tmp" table
;with cte(id,seq,char,rest) as (
    select id,1,cast(left(statename,1) as varchar(2)), stuff(statename,1,1,'')
      from #tmp
     union all
    select id,seq+1,case when ascii(left(rest,1)) between ascii('A') and ascii('Z')
                         then ' ' else '' end + left(rest,1)
         , stuff(rest,1,1,'')
      from cte
     where rest > ''
), recombined as (
  select a.id, (select b.char+''
                  from cte b
                 where a.id = b.id
              order by b.seq
                   for xml path, type).value('/','varchar(100)') fixed
    from cte a
group by a.id
)
update t
   set statename = c.fixed
  from #tmp t
  join recombined c on c.id = t.id
 where statename != c.fixed;

-- check the result
select * from #tmp

----------- -----------
id          statename
----------- -----------
1           North Carolina
2           South Carolina
3           New South Wales