1

我正在做一个项目并停留在一个sql query,查询没有给出任何错误也没有返回任何结果告诉我问题出在哪里

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

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

如果运行这个

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

它返回值

4

3 回答 3

7

SQL Server 不会扩展'@year-07-%'.

假设@year参数是 avarchar并且[date]列是 a date,你可以试试这个:

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

甚至更好:

where  datepart(year, [date]) = cast(@year as int)
       and datepart(month, [date]) = 7
于 2013-07-29T09:26:59.727 回答
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))
于 2013-07-29T10:10:01.387 回答
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
于 2013-07-29T10:39:35.987 回答