除了空格外,如何用星号替换字符串中的所有字符?

时间:2013-05-15 21:43:42

标签: sql sql-server sql-server-2008 tsql

您好我不擅长SQL,所以任何帮助都会非常好,谢谢。

我有一个包含2列字和替换

的表格

现在我的替换列为null但是我正在尝试执行更新语句,该语句计算来自world列的字符,然后将特定符号添加到替换列

例如,word列中的值是Hello World,更新将添加

Hello World, ***** *****

现在我很简单

update Words
set replacement = Replace(words, '*')

2 个答案:

答案 0 :(得分:1)

这是您可以用来执行此类更新的功能。

它使用一个数字表,如果你还没有,你可以read more here(创建一个!)。

create function dbo.ReplaceChars(@Word varchar(max), @Char char(1))
returns varchar(max)
as
begin

    declare @output varchar(1000);
    set @output = replicate(@Char, len(@Word));

    select  @output = stuff(@output, n, 1, ' ')
    from    (   select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union 
                select 7 union select 8 union select 9 union select 10 union select 11 union select 12
            ) number(n) --** use your own number table here **
    where   substring(@Word, n, 1) = ' ' and 
            n <=len(@Word);

   return @output;

end



--usage
declare @table table (Word varchar(max), Replacement varchar(max))
insert into @table (Word)
    select 'Hello World' union all
    select 'one two yak';

update  @table
set     Replacement = dbo.ReplaceChars(Word, '*')
where   Word is not null;

select * from @table;

答案 1 :(得分:0)

使用复制功能,您可以轻松完成您想要做的事情。

复制( '*',LEN(字))

示例:

declare @test table (
     word varchar(100)
    ,replacement varchar(100)
)

insert into @test
values
 ('bad',null)
,('word',null)

select
     word test1
    ,replacement test1
from @test

update @test
set replacement = replicate('*',len(word))
where replacement is null

select
     word test2
    ,replacement test2
from @test
相关问题