Datepart的SQL情况

时间:2019-02-25 16:13:29

标签: sql sql-server sql-server-2008

在使用datepart时,我遇到SQL案例的困难。不断得到 “消息102,级别15,状态1,第4行。'='附近的语法不正确。”

确实需要帮助来解决此问题:(

Update <Table name>
Set Shiftcode = 
Case indttime
When datepart(hour,indttime) = 7 then 'ShiftM'
When datepart(hour,indttime) = 9 then 'Shift2'
Where (shiftcode = 'Shifwn' or shiftcode = 'shifwm') 
and (shiftdate > '2019-01-10 00:00:00:000' and shiftdate < '2019-02-11 00:00:00:000')
and staffno in (
Select distinct staffno
from <Table name>
where (shiftcode = 'Shifwn' or shiftcode = 'shiftwm')
and (shifdate > '2019-01-10 00:00:00:000' and shiftdate < '2019-02-11 00:00:00:000'));

此代码有什么问题吗?

3 个答案:

答案 0 :(得分:0)

您错过了案例表达中的end

Update <Table name>
Set Shiftcode = 
Case When datepart(hour,indttime) = 7 then 'ShiftM'
When datepart(hour,indttime) = 9 then 'Shift2'
else null end
Where (shiftcode = 'Shifwn' or shiftcode = 'shifwm') 
and (shiftdate > '2019-01-10 00:00:00:000' and shiftdate < '2019-02-11 00:00:00:000')
and staffno in (
Select distinct staffno
from <Table name>
where (shiftcode = 'Shifwn' or shiftcode = 'shiftwm')
and (shifdate > '2019-01-10 00:00:00:000' and shiftdate < '2019-02-11 00:00:00:000'));

答案 1 :(得分:0)

您的代码一团糟。我怀疑你想要

update <Table name>
    set Shiftcode = (case when datepart(hour, indttime) = 7 then 'ShiftM'
                          when datepart(hour, indttime) = 9 then 'Shift2'
                     end)
Where shiftcode in ('Shifwn', 'shifwm') and
      datepart(hour, indttime) in (7, 9) and
      shiftdate > '2019-01-10' and shiftdate < '2019-02-11';

这将在where中提到的两个班次在指定时间开始的指定日期收取班次名称。

答案 2 :(得分:0)

如果不设置格式,则很难快速检测是否缺少END之类的关键字。始终格式化代码并缩进逻辑块(无论使用哪种语言)。

Update <Table name>
Set Shiftcode =
     Case /*indttime this should not be here*/
        When datepart(hour,indttime) = 7 then 'ShiftM'
        When datepart(hour,indttime) = 9 then 'Shift2'
    end /*end was missing here*/
Where /*(
        shiftcode = 'Shifwn'
    or  shiftcode = 'shifwm'
) This can be replaced with IN */
shiftcode IN ('Shifwn','shifwm')
and shiftdate > '2019-01-10 00:00:00:000'
and shiftdate < '2019-02-11 00:00:00:000'
and staffno in (
    Select distinct staffno
    from <Table name>
    where /*(
            shiftcode = 'Shifwn'
        or  shiftcode = 'shiftwm'
    ) This can be replaced with IN */
    shiftcode IN ('Shifwn','shiftwm')
    and shifdate > '2019-01-10 00:00:00:000'
    and shiftdate < '2019-02-11 00:00:00:000'
);

仅供参考,WHERE和子选择项之间的移位代码不匹配。