SQL 服务器- if else/case when 语句

SQL Server- if else/case when statement

我在 select 查询中写了一个 case 语句,如下所示。我不确定 SQL 服务器中 If else 的语法,而且我想使用 'as' 命名该列,但它在 'as' 附近抛出错误语法错误。请帮忙。 T

select 
    a.account_id as [Account Id],
    substring(a.account_id,1,3) as [Company ID],
    substring(a.account_id,4,6) as [Account No],
    substring(a.account_id,10,5) as [Cost Center],
    b.amount as Amount,
    b.period as Period,
    getdate() as SysDate,
    format(getdate(), 'mm/dd/yyyy') as SYSDtText,
    substring('SYSDtText',1,2) as [Current Period],
    b.year_budget as [Year Budget],
    substring('SYSDtText', 7, 4 ) as SysDtYearText,
    case 
       when Period <= 'Current Period' 
          then 'include' 
          else '' 
    as [Period Include Flag], 
    a.description as [Description]
from 
    period_summary b
inner join 
    account a on b.account_id = a.account_id;

您缺少 "end"

正确:

CASE WHEN Period<='Current Period' then 'include' else '' end as [Period Include Flag]

我认为你需要更改这一行:

CASE WHEN Period<='Current Period' then 'include' else '' as [Period Include Flag], 

对此:

CASE WHEN Period <= substring('SYSDtText',1,2) then 'include' else '' end as [Period Include Flag], 

目前您正在将 [Period] 与字符串文字 'Current Period' 进行比较——我认为这不是您打算做的,因为您的查询中有一列名为 [Current Period]。