日期:2014-05-17  浏览次数:20498 次

一个简单的SQL语句,大家写写看!
有很多数据,格式是这样的
由数字与逗号、或是纯数字组成 或是NULL

如果有逗号,就截取第一个逗号之前的数字,没有逗号就直接返回数字,这样的SQL怎么写

123,11,74512
1354534,1545
456465
NULL

查询结果
123
1354534
456465
NULL
截断字符串 SQL

------解决方案--------------------
select case when charindex(',',col)>0 then left(col,charindex(',',col)-1) else col end
from tb

------解决方案--------------------
create table #tb(col varchar(100))
insert into #tb
select '123,11,74512'
union all select '1354534,1545'
union all select '456465'
union all select NULL

select case when charindex(',',col)>0 then left(col,charindex(',',col)-1) else col end
from #tb
drop table #tb

/*
123
1354534
456465
NULL
*/

------解决方案--------------------
借用下楼上的数据。

create table #tb(col varchar(100))
insert into #tb
select '123,11,74512'
union all select '1354534,1545'
union all select '456465'
union all select NULL
select left(col,charindex(',',col+',')-1) from #tb