某一字段为nvarchar类型,怎样查询得到该字段中包含有数字的纪录?怎样将数字用''替换掉?比如:ID A
------------
1 abcd
2 a12b
3 c4
4 ef查询得到:
ID A
------------
2 a12b
3 c4
------------
1 abcd
2 a12b
3 c4
4 ef查询得到:
ID A
------------
2 a12b
3 c4
调试欢乐多
select *
from tablename
where patindex('%[0-9]%',A)>0
------------
1 abcd
2 a12b
3 c4
4 ef要变成:
ID A
------------
1 abcd
2 ab
3 c
4 ef
from tablename
where when patindex('%[0-9]%',A)>0 then replace(A,'[0-9]','') else A END
如何实现字符串中首位的P用''替换?
比如:
ID A
---------
1 PabcP
2 abcPc
3 Pef变化为:
ID A
-----------
1 abcP
2 abcPc
3 ef就是说除非P出现在首位,否则不替换
或者
UPDATE tb SET A=STUFF(A,1,1,'') WHERE LEFT(A,1)='P'
------------------------------------------------------------------------------------
用replace()一次实现不了,因为replace不支持通配符.可以创建个专门的函数来进行替换.
if object_id('fn_Replace') is not null
drop function fn_Replace
go
----创建替换数字的函数
create function fn_Replace(@SourceString varchar(100))
returns varchar(100)
as
begin
while patindex('%[0-9]%',@SourceString) > 0
set @SourceString = stuff(@SourceString,patindex('%[0-9]%',@SourceString),1,'')
return @SourceString
end
go
----创建测试数据
declare @t table(id int,A varchar(10))
insert @t
select 1,'abcd' union all
select 2,'a12b' union all
select 3,'c4' union all
select 4,'ef'
----查询
select id,dbo.fn_Replace(A) from @t--drop function fn_Replace
功能太强了。居然patindex('%[a,c,e,f]%',A)>0 也可以查找倒相应记录。