通配符sql日期查询

时间:2013-07-29 09:23:14

标签: asp.net sql sql-server

我正在处理一个项目,并坚持sql query,查询不会给出任何错误,也不会返回任何结果告诉我问题出在哪里

SELECT
      barcode
    , Date
    , timein
    , timeout
    , totaltime
    , leave
    , remarks
FROM TimeSheet
WHERE barcode = @barcode
     AND Date LIKE '@year-07-%'

我在运行时@barcode @year传递变量中的2个值 但是如果我在sql编辑器中显式运行带有值类型的查询,它可以正常工作并返回值

如果运行此

SELECT
      barcode
    , Date
    , timein
    , timeout
    , totaltime
    , leave
    , remarks
FROM TimeSheet
WHERE barcode = 123456
     AND Date LIKE '2013-07-%'

它返回值

3 个答案:

答案 0 :(得分:7)

SQL Server不会在'@year-07-%'中展开变量。

假设@year参数是varchar[date]列是date,您可以尝试这样做:

where  convert(varchar(10), [date], 120) like @year + '-07-%'

甚至更好:

where  datepart(year, [date]) = cast(@year as int)
       and datepart(month, [date]) = 7

答案 1 :(得分:3)

如果DATE列上有索引

,以下内容将会有效
SELECT
      barcode
    , Date
    , timein
    , timeout
    , totaltime
    , leave
    , remarks
FROM TimeSheet
WHERE barcode = @barcode
     AND Date >=dateadd(month,6,dateadd(year,@year-1900,0))
     AND Date <dateadd(month,7,dateadd(year,@year-1900,0))

答案 2 :(得分:1)

这是Andomar所建议的。

create table #timesheet (barcode int, entrydate date, other_col varchar(20))

insert into #timesheet (barcode, entrydate , other_col)
values (123456,'2013-07-01','helloA')
    ,(123456,'2013-07-02','helloB')
    ,(123457,'2013-07-02','helloC')
    ,(123456,'2013-06-01','helloD')

DECLARE @YEAR VARCHAR(4) = '2013'
    ,@barcode int = 123456

Select *
From #timesheet
Where barcode = @barcode
And convert(varchar(10), entrydate, 120) like @year + '-07-%'

Select *
From #timesheet
Where barcode = @barcode
And datepart(year,entrydate) = cast(@year as int)
And datepart(month,entrydate) = 7