Search code examples
sql-serversql-server-2008ms-accessiif

Convert IIF() Access statement to SQL Server


I am trying to convert a access code into sql 2008. But just found out sql 2008 doesn't support the IIF statement! Here are two ways that I am trying to rewrite my query, I know I am messing up with the syntax:

select distinct (IIf(IsNull([dbo_TASK]![act_start_date])
,IIf(IsNull([dbo_TASK]![restart_date]),[dbo_TASK]![target_start_date],[dbo_TASK]![restart_date]),[dbo_TASK]![act_start_date]) AS [Estimated Start Date] from dbo.task

ATTEMPT1:
if dbo.task.act_start_date=null
    then
        if(dbo.task.restart_date=null)
            then dbo.task.target_start_date
        else dbo.task.restart_date
    else dbo.task.act_start_date


ATTEMP2:
select (case when dbo.task.act_start=null then 
                (case when dbo.task.restart_date=null
                then (dbo.task.target_start_date)
                else dbo.task.restart_date
                end)                
    else (dbo.task.act_start_date)
    end) from dbo.task

Solution

  • Your query was very close. When checking if a value is equal to null you use Is Null not =null

    So if you implement that you can use the following:

    select distinct 
        case 
            when [act_start_date] is null
            then 
                case 
                    when [restart_date] is null
                    then [target_start_date]
                    else [restart_date]
            else [act_start_date] 
        end AS [Estimated Start Date] 
    from dbo.task
    

    Or even easier you can use COALESCE() which will return the first non-null value:

    select distinct 
        coalesce([act_start_date], [restart_date], [target_start_date]) as [Estimated Start Date] 
    from dbo.task