SQL 日期部分大小写

SQL Case When Datepart

我在 SQL 使用 datepart 时遇到问题。不断得到 "Msg 102, Level 15, State 1, Line 4. Incorrect syntax near '='".

真的需要帮助来解决这个问题:(

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

这段代码有什么问题吗?

你错过了 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'));

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

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中提到的两个班次的班次名称收费,在指定的日期,当他们在指定的时间开始。

如果不进行格式化,则很难快速检测出是否缺少 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 和 sub-select 之间的 shiftcode 不匹配。