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

求一日期大小比较的SELECT语句
本帖最后由 gzpydc 于 2012-11-17 14:30:40 编辑

' 表[Table1]
' Id           Comment            Title
'----------------------------------------------------
'  1    2011-3-4,CNCQ,2011-3-6     重庆
'  2             CNSH              上海
'  3    2011-3-6,CNWH,             武汉
'  4            ,CNDL,2011-3-9     大连
'  5         <NULL>                未选择
'  6    2011-3-5,,2011-3-6         未选择
'  7    2011-3-1,CNQD,2011-4-8     青岛
'
'  用SELECT语句如何写,才可以在Comment字段中获取
'  日期介乎于 2011-3-5至2011-3-7之间的所有记录
'  得出如下期望返回结果集?
'
'  实际情况中,某些记录的Comment字段为空值 <NULL>,如第5行记录
'  除此之外,也并不全都是固定的 ,, 数组格式,如第2行记录
'
' 期望结果
' Id           Comment            Title
'----------------------------------------------------
'  6    2011-3-5,,2011-3-9         未选择

------解决方案--------------------
declare @a datetime = '2011-3-5', @b datetime = '2011-3-7';
with a(Id,Comment,Title) as
(
select 1, '2011-3-4,CNCQ,2011-3-6', '重庆' union all
select 2, 'CNSH', '上海' union all
select 3, '2011-3-6,CNWH,', '武汉' union all
select 4, ',CNDL,2011-3-9', '大连' union all
select 5, NULL, '未选择' union all
select 6, '2011-3-5,,2011-3-6', '未选择' union all
select 7, '2011-3-1,CNQD,2011-4-8', '青岛'
), b as
(
select *, m = charindex(',',Comment), n = charindex(',',Comment,charindex(',',Comment)+1) from a
)
select Id,Comment,Title from b where m<n and left(Comment,m-1)>=@a and nullif(substring(Comment,n+1,99),'')<=@b
/*
 Id           Comment            Title
----------------------------------------------------
  6    2011-3-5,,2011-3-9         未选择
*/