首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

求SQL替换某字符的语句,只替换左起第一位解决方案

2012-02-06 
求SQL替换某字符的语句,只替换左起第一位如,在表table1字段为aa中的两条数据为 Q1234Q , Q4321L 要把Q替换

求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 table1set 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 allselect 'Q4321'update table1 set aa=stuff(aa,1,1,'L') where left(aa,1)='Q' select * from [table1]/*aa------L1234QL4321*/
[解决办法]
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'
[解决办法]
用来用去就是几个函数,你们都有神了啊

热点排行
Bad Request.