日期:2014-05-18  浏览次数:20814 次

求SQL替换某字符的语句,只替换左起第一位
如,在表table1字段为aa中的两条数据为 Q1234Q , Q4321L 要把Q替换成L我可以用如下语句

update table1 set aa=replace(aa,'Q','L') 

但要求是把左起第一位是Q的替换L,只替换第一位,怎么写?

------解决方案--------------------
SQL code

update table1 set aa= case when left(aa,1)='Q' then 'L'+right(aa,len(aa)-1) else aa end
--或者
update table1 set aa= 'L'+right(aa,len(aa)-1) 
where left(aa,1)='Q'

------解决方案--------------------
SQL code
update table1 set aa=stuff(aa,1,1,'L') where left(aa,1)='Q'

------解决方案--------------------
探讨
如,在表table1字段为aa中的两条数据为 Q1234Q , Q4321L 要把Q替换成L我可以用如下语句

update table1 set aa=replace(aa,'Q','L')

但要求是把左起第一位是Q的替换L,只替换第一位,怎么写?

------解决方案--------------------
探讨
SQL code
update table1 set aa=stuff(aa,1,1,'L') where left(aa,1)='Q'

------解决方案--------------------
SQL code

update table1
set aa=stuff(aa,charindex('Q',aa),1,'L')
where aa like '%Q%'

------解决方案--------------------
update table1 set aa=stuff(aa,1,1,'L') where left(aa,1)='Q'
------解决方案--------------------
SQL code

if object_id('[table1]') is not null 
drop table [table1]

create table [table1] (aa varchar(6))
insert into [table1]
select 'Q1234Q' union all
select 'Q4321'

update table1 set aa=stuff(aa,1,1,'L') where left(aa,1)='Q' 
select * from [table1]
/*
aa
------
L1234Q
L4321
*/

------解决方案--------------------
create table tbl(
id varchar(20) not null,
name varchar(20) not null
)

insert into tbl values('Q0411tracy','tracy')
insert into tbl values('M0917kobe','kobe')
insert into tbl values('Q0574tom','tom')
insert into tbl values('N0755lucy','lucy')
select *from tbl

update tbl set id='L'+right(id,len(id)-1) where left(id,1)='Q'
------解决方案--------------------
用来用去就是几个函数,你们都有神了啊