Search code examples
sqlcaseadvantage-database-server

Case within string insert into


I have the below insert into string statement, but the Case part of it seems to break it. If the value of Paymenttype from a particular table is TNP1, then I want it to use one particular value, and if TNP2, then I need another value to be used. Instead I get an error saying there's an issue with my WHEN expression in my Case. Any ideas? Using Advantage Arc.

open cur as 
select
'insert into pctrnpay'+char(10)+
'('+char(10)+
'ident,'+char(10)+
'actual,'+char(10)+
'sys_type,'+char(10)+
'actualamt,'+char(10)+
'descrip,'+char(10)+
'status,'+char(10)+
'expected,'+char(10)+
'expamt,'+char(10)+
')'+char(10)+
'values'+char(10)+
'('+char(10)+
iif(internalident is not null,char(39)+trim(cast(internalident as 
sql_char(5)))+char(39),'Null')+','+char(13)+char(10)+
iif(financialdate is not null,char(39)+trim(cast(financialdate as 
sql_char(10)))+char(39),'Null')+','+char(13)+char(10)+
iif(paymenttype is not null,char(39)+'APTB_'+trim(cast(paymenttype as 
sql_char(10)))+char(39),'Null')+','+char(13)+char(10)+
iif(amount is not null,trim(cast(amount as 
sql_char(4))),'Null')+','+char(13)+char(10)+
char(39)+ case paymenttype  when paymenttype='TNP1' then 'App Total 
Negotiated Price - Training'
                        when paymenttype='TNP2' then 'App Total Negotiated 
Price - Assessment'
                        end +char(39)+','+char(13)+char(10)+
');'+char(10)+char(10) str_SQL
from [..\_control\pics.add]._FinancialDetails ;

Solution

  • You currently have:

    CASE paymenttype
      WHEN paymenttype = 'TNP1' THEN ...
      WHEN paymenttype = 'TNP2' THEN ...
    END
    

    This is not a valid form for CASE expressions, you are mixing simple and searched CASE forms.

    A simple CASE looks like this:

    CASE paymenttype
      WHEN 'TNP1' THEN ...
      WHEN 'TNP2' THEN ...
    END
    

    While a searched CASE looks like this:

    CASE
      WHEN paymenttype = 'TNP1' THEN ...
      WHEN paymenttype = 'TNP2' THEN ...
    END
    

    Both are equivalent, so you can choose from one of these two forms.