DECODE( ) function in SQL Server

后端 未结 8 1888
傲寒
傲寒 2020-12-03 04:42
SELECT PC_COMP_CODE,
       \'R\',
       PC_RESUB_REF,
       DECODE(PC_SL_LDGR_CODE, \'02\', \'DR\', \'CR\'),
       PC_DEPT_NO DEPT,
       \'\', --PC_DEPT_NO,
           


        
相关标签:
8条回答
  • 2020-12-03 05:02

    Create a function in SQL Server as below and replace the DECODE with dbo.DECODE

    CREATE FUNCTION DECODE(@CondField as nvarchar(100),@Criteria as nvarchar(100), 
                           @True Value as nvarchar(100), @FalseValue as nvarchar(100))
    returns nvarchar(100)
    begin
           return case when @CondField = @Criteria then @TrueValue 
                       else @FalseValue end
    end
    
    0 讨论(0)
  • 2020-12-03 05:06

    It's easy to do:

    select 
        CASE WHEN 10 > 1 THEN 'Yes'
        ELSE 'No'
    END 
    
    0 讨论(0)
  • 2020-12-03 05:08

    when I use the function

    select dbo.decode(10>1 ,'yes' ,'no')
    

    then say syntax error near '>'

    Unfortunately, that does not get you around having the CASE clause in the SQL, since you would need it to convert the logical expression to a bit parameter to match the type of the first function argument:

    create function decode(@var1 as bit, @var2 as nvarchar(100), @var3 as nvarchar(100))
    returns nvarchar(100)
    begin
    return case when @var1 = 1 then @var2 else @var3 end;
    end;
    
    select dbo.decode(case when 10 > 1 then 1 else 0 end, 'Yes', 'No');
    
    0 讨论(0)
  • 2020-12-03 05:09

    Just for completeness (because nobody else posted the most obvious answer):

    Oracle:

    DECODE(PC_SL_LDGR_CODE, '02', 'DR', 'CR')
    

    MSSQL (2012+):

    IIF(PC_SL_LDGR_CODE='02', 'DR', 'CR')
    

    The bad news:

    DECODE with more than 4 arguments would result in an ugly IIF cascade

    0 讨论(0)
  • 2020-12-03 05:10

    join this "literal table",

    select 
        t.c.value('@c', 'varchar(30)') code,
        t.c.value('@v', 'varchar(30)') val
    from (select convert(xml, '<x c="CODE001" v="Value One" /><x c="CODE002" v="Value Two" />') aXmlCol) z
    cross apply aXmlCol.nodes('/x') t(c)
    
    0 讨论(0)
  • 2020-12-03 05:11

    You could use the 'CASE .. WHEN .. THEN .. ELSE .. END' syntax in SQL.

    0 讨论(0)
提交回复
热议问题