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 に答える
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 に答える