SQL Server- if else / case when语句

时间:2018-03-12 17:11:06

标签: sql-server sql-server-2008 if-statement sql-server-2012 case-when

我在select查询中写了一个case语句,如下所示。我不确定SQL Server中If else的语法,我也想使用'作为'来命名列。但它的错误表示错误的语法接近'。请帮忙。 Ť

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;

2 个答案:

答案 0 :(得分:2)

您错过了&#34;结束&#34;

正确:

{{1}}

答案 1 :(得分:0)

我认为您需要更改此行:

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], 

目前,您正在将[期间]与字符串文字&#39;当前期间&#39;进行比较。 - 我不认为这是您打算做的,因为您的查询中有一列称为[当前期间]。