当前位置: 代码迷 >> Sql Server >> 如何样把替换后的字符合并成新的字符串
  详细解决方案

如何样把替换后的字符合并成新的字符串

热度:34   发布时间:2016-04-27 17:39:56.0
怎么样把替换后的字符合并成新的字符串?
Declare   @Str   Varchar(20)
Declare   @Postion   Int
Set   @Str= 'abcdefgh@ '
Set   @postion=1
While   @Postion <DATALENGTH(@Str)+1
Begin
Select   Replace(SUBSTRING(@Str,@Postion,1), '@ ', ' ')
Set   @[email protected]+1
End
[email protected],但是我在我合并的时候却市NULL.


------解决方案--------------------
Declare @Str Varchar(20)
Declare @Postion Int
Set @Str= 'abcdefgh@ '
Set @postion=1

declare @re varchar(20)
set @re = ' '
While @Postion <DATALENGTH(@Str)+1
Begin
Select @re = @re + Replace(SUBSTRING(@Str,@Postion,1), '@ ', ' ')
Set @[email protected]+1
End
Select @re
------解决方案--------------------
不过, 直接 replace 不就行了吗? 干嘛用循环?

Declare @Str Varchar(20)
Set @Str= 'abcdefgh@ '
select replace(@str, '@ ', ' ')

-- 结果: abcdefgh
------解决方案--------------------

Declare @Str Varchar(20)
Declare @Postion Int
Declare @NewStr varchar(20)
set @newstr= ' '
Set @Str= 'abcdefgh@ '
Set @postion=1
While @Postion <DATALENGTH(@Str)+1
Begin
if substring(@Str,@postion,1) <> '@ '
set @[email protected]+substring(@Str,@postion,1)
set @[email protected]+1
End
select @Newstr
---
abcdefgh
------解决方案--------------------
是啊,为什么用循环?replace就可以略去字符串中的非法字符啊。
  相关解决方案