Datepart时的SQL案例

问题描述 投票:1回答:3

使用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'));

这段代码有什么问题吗?

sql sql-server sql-server-2008
3个回答
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'));

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中提到的两个班次的班次名称,这些班次是在指定时间开始的指定日期。


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和子选择之间不匹配。

© www.soinside.com 2019 - 2024. All rights reserved.