SQL Server CASE then statement error - sql

I have a pretty simple Stored Procedure that I'm trying to add a case then statement in the Where Statement. I keep getting an error message:
Msg 156, Level 15, State 1, Procedure Proc_AssuranceBilling_rpt, Line 36
Incorrect syntax near the keyword 'Case'.
I don't know why. Can someone please look and tell me what I've done wrong?
WHERE
e.[DDEventDesc] IN (SELECT #rptType
Case WHEN 'Payroll - Audit' THEN ('Payroll - Audit')
WHEN 'Audits' Then ('Audit - Aup', 'Audit - EBP', 'Audit- Financial Institutions','Audit - Governmental','Audit - HUD','Audit - Not-for-Profit','Audit - Personal Property Tax','Audit - Single Audit','Audit - Small Business')
WHEN 'Review & Comps' Then ('Audit - Review', 'Audit -Comp/Disc','Audit - Comp w/o Disc')
WHEN 'Assur Tax Returns' THEN ('5500','720-PCORI','8955-SSA','Campaign Report','Corporate (1120-POL)','LM-1','LM-2','LM-3','LM-4','LM-10','LM-30','Non-Profit (990)','Non-Profit (990 EZ)','Non-Profit (990-N)','Non-Profit (990-T)','Schedule C Letters','Section 104D Letter')
END)
AND AR.[ARType] = 1
AND (CLT.[cmaster] = 1 OR CLT.[cinvIndivEng] = 0)

I think you need to rewrite your WHERE clause as:
WHERE ((#rptType = 'Payroll - Audit' AND e.[DDEventDesc] = 'Payroll - Audit') OR
(#rptType = 'Audits' AND e.[DDEventDesc] IN ('Audit - Aup',
'Audit - EBP',
'Audit- Financial Institutions',
'Audit - Governmental',
'Audit - HUD',
'Audit - Not-for-Profit',
'Audit - Personal Property Tax',
'Audit - Single Audit',
'Audit - Small Business') OR
(#rptType = 'Review & Comps' AND e.[DDEventDesc] IN ('Audit - Review', 'Audit -Comp/Disc','Audit - Comp w/o Disc')) OR
(#rptType = 'Assur Tax Returns' AND e.[DDEventDesc] IN ('5500','720-PCORI','8955-SSA','Campaign Report','Corporate (1120-POL)','LM-1','LM-2','LM-3','LM-4','LM-10','LM-30','Non-Profit (990)','Non-Profit (990 EZ)','Non-Profit (990-N)','Non-Profit (990-T)','Schedule C Letters','Section 104D Letter') )
AND AR.[ARType] = 1
AND (CLT.[cmaster]=1 OR CLT.[cinvIndivEng] = 0)
CASE cannot be used to return multiple values. From MSDN on CASE:
Syntax:
Simple CASE expression:
CASE input_expression
WHEN when_expression THEN result_expression [ ...n ]
[ ELSE else_result_expression ]
END
Searched CASE expression:
CASE
WHEN Boolean_expression THEN result_expression [ ...n ]
[ ELSE else_result_expression ]
END
THEN result_expression Is the expression returned when
input_expression equals when_expression evaluates to TRUE, or
Boolean_expression evaluates to TRUE. result expression is any valid
expression.
And what can any valid expression be? According to Expressions:
Is a combination of symbols and operators that the SQL Server Database
Engine evaluates to obtain a single data value.

the variable #rptType should be the case variable .. u placed it out side the case
try this..
WHERE e.[DDEventDesc] IN ( SELECT Case #rptType
WHEN 'Payroll - Audit' THEN ('''Payroll - Audit''')
WHEN 'Audits' Then ('''Audit - Aup, Audit - EBP'', ''Audit- Financial Institutions'',''Audit - Governmental'',''Audit - HUD'',''Audit - Not-for-Profit'',''Audit - Personal Property Tax'',''Audit - Single Audit,Audit - Small Business''')
WHEN 'Review & Comps' Then ('''Audit - Review'', ''Audit -Comp/Disc'',''Audit - Comp w/o Disc''')
WHEN 'Assur Tax Returns' THEN ('''5500'',''720-PCORI'',''8955-SSA'',''Campaign Report'',''Corporate (1120-POL)'',''LM-1'',''LM-2'',''LM-3,''LM-4,''LM-10'',''LM-30'',''Non-Profit (990)'',''Non-Profit (990 EZ)'',''Non-Profit (990-N)'',''Non-Profit (990-T)'',''Schedule C Letters'',''Section 104D Letter''')
END
)
AND AR.[ARType] = 1
AND (CLT.[cmaster]=1 OR CLT.[cinvIndivEng] = 0)

Related

Filtering rows conditionally within a query to further filter the query result in postgres

I have mostly worked with NoSql dbs but I'm trying my hands at SQL after a very long while. I have a table named invoices.
id
invoice_type
valid_until
01
quote
2023-03-10
02
quote
2021-03-10
03
reservation
2022-03-11
I'm trying to filter rows on a query param named type
If type = reservation, Return all rows with invoice_type = reservation
If type = quote, Return all rows with invoice_type = quote AND valid_until > now()
If type = undefined || invalid, Return rows of both types but for rows with invoice_type = quote still filter them out based on the valid_until field.
I'm struggling with the 3rd rule, the idea is to get all rows and then apply the filter for valid_until only on the rows with type = quote
Expected Output
GET api/invoices?type=quote
{ id: 01, invoice_type: 'quote', valid_until: '2023-03-10' }
GET api/invoices?type=reservation
{ id: 03, invoice_type: 'reservation', valid_until: '2022-03-11' }
GET api/invoices
[
{ id: 01, invoice_type: 'quote', valid_until: '2023-03-10' },
{ id: 03, invoice_type: 'reservation', valid_until: '2022-03-11' }
]
Current solution is
const invoices = await knex('invoices').where((builder) => {
switch (type) {
case 'quote':
builder.where({ type }).where('valid_until', '>', 'now()');
break;
case 'reservation':
builder.where({ type });
break;
default:
console.log(type);
builder
.where({ type: 'quote' })
.where('valid_until', '>', 'now()')
.orWhere({ type: 'reservation' });
break;
}
});
It's working but I was hoping to achieve this purely through SQL.
A where clause in a parameterized query can do all this. Here it is. :type is the parameter.
select * from invoices
where
(:type = 'reservation' AND invoice_type = 'reservation')
OR (:type = 'quote' AND invoice_type = 'quote' AND valid_until > now())
OR (:type in ('undefined', 'invalid') AND case
when invoice_type = 'quote' then valid_until > now()
else true
end
);

If statements with SQL and returning string values

I'm using SQL and I need to return one string if the value of a field is 5 and another string if the value of the field is 4. I have something like this right now:
SELECT * FROM tablename WHERE value1=4 OR value1=5;
In PHP for example it might be like this (but I can't use PHP for my application):
if ($value1 == 4) {
$value1 = 'free';
} elseif ($value1 == 5) {
$value1 = 'not free';
} elseif...etc.
Anyone know how to accomplish what I want with SQL only?
Then you would do something like:
select (case when value1 = 4 then 'free' else 'not free' end) as newval
from tablename
where value1 in (4, 5);

Oracle throws ORA-00911 invalid character error while executing a query generated by entity framework 6.0

I'm having problems with the query below which is generated by Entity Framewrok 6.0. When I remove where clause query is being executed well. But I cant see the problem on where clause. Can you please help me?
{SELECT
"Extent1"."ID" AS "ID",
"Extent1"."STATECODE" AS "STATECODE",
"Extent1"."FIRMAID" AS "FIRMAID",
"Extent1"."ILID" AS "ILID",
"Extent1"."ILCEID" AS "ILCEID",
"Extent1"."PLANTURID" AS "PLANTURID",
"Extent1"."ETUDTURID" AS "ETUDTURID",
"Extent1"."ETUDAMACID" AS "ETUDAMACID",
"Extent1"."DILIMID" AS "DILIMID",
"Extent1"."ACIKLAMA" AS "ACIKLAMA",
"Extent1"."BASVURUTARIHI" AS "BASVURUTARIHI",
"Extent1"."ALAN" AS "ALAN",
"Extent1"."OLCEK" AS "OLCEK",
"Extent1"."CREATETIME" AS "CREATETIME",
"Extent1"."UPDATETIME" AS "UPDATETIME",
"Extent1"."CREATEUSERID" AS "CREATEUSERID",
"Extent1"."UPDATEUSERID" AS "UPDATEUSERID",
"Extent2"."ID" AS "ID1",
"Extent2"."KOD" AS "KOD",
"Extent2"."AD" AS "AD",
"Extent2"."CREATETIME" AS "CREATETIME1",
"Extent2"."UPDATETIME" AS "UPDATETIME1",
"Extent2"."CREATEUSERID" AS "CREATEUSERID1",
"Extent2"."UPDATEUSERID" AS "UPDATEUSERID1",
"Extent3"."ID" AS "ID2",
"Extent3"."KOD" AS "KOD1",
"Extent3"."AD" AS "AD1",
"Extent3"."PLANTURID" AS "PLANTURID1",
"Extent3"."CREATETIME" AS "CREATETIME2",
"Extent3"."UPDATETIME" AS "UPDATETIME2",
"Extent3"."CREATEUSERID" AS "CREATEUSERID2",
"Extent3"."UPDATEUSERID" AS "UPDATEUSERID2",
"Extent4"."ID" AS "ID3",
"Extent4"."VERGINUMARASI" AS "VERGINUMARASI",
"Extent4"."EMAIL" AS "EMAIL",
"Extent4"."FIRMAADI" AS "FIRMAADI",
"Extent4"."BUROTESCILNUMARASI" AS "BUROTESCILNUMARASI",
"Extent4"."TELEFON" AS "TELEFON",
"Extent4"."ADRES" AS "ADRES",
"Extent4"."ILID" AS "ILID1",
"Extent4"."ILCEID" AS "ILCEID1",
"Extent4"."MAHALLEID" AS "MAHALLEID",
"Extent4"."VERGIDAIRESIID" AS "VERGIDAIRESIID",
"Extent4"."USERID" AS "USERID",
"Extent4"."NODEID" AS "NODEID",
"Extent4"."CREATETIME" AS "CREATETIME3",
"Extent4"."UPDATETIME" AS "UPDATETIME3",
"Extent4"."CREATEUSERID" AS "CREATEUSERID3",
"Extent4"."UPDATEUSERID" AS "UPDATEUSERID3",
"Extent5"."FEATUREID" AS "FEATUREID",
"Extent5"."ADI_NUMARASI" AS "ADI_NUMARASI",
"Extent5"."UAVTKOD" AS "UAVTKOD",
"Extent6"."FEATUREID" AS "FEATUREID1",
"Extent6"."ADI_NUMARASI" AS "ADI_NUMARASI1",
"Extent6"."UAVTKOD" AS "UAVTKOD1",
"Extent6"."ILKOD" AS "ILKOD",
"Extent7"."ID" AS "ID4",
"Extent7"."ENLEM" AS "ENLEM",
"Extent7"."BOYLAM" AS "BOYLAM",
"Extent7"."DILIMI" AS "DILIMI",
"Extent7"."MERIDYEN" AS "MERIDYEN",
"Extent7"."ILADI" AS "ILADI",
"Extent7"."ILID" AS "ILID2",
"Extent8"."ID" AS "ID5",
"Extent8"."KOD" AS "KOD2",
"Extent8"."AD" AS "AD2",
"Extent8"."CREATETIME" AS "CREATETIME4",
"Extent8"."UPDATETIME" AS "UPDATETIME4",
"Extent8"."CREATEUSERID" AS "CREATEUSERID4",
"Extent8"."UPDATEUSERID" AS "UPDATEUSERID4"
FROM "JEOLOJI"."PROJE" "Extent1"
INNER JOIN "JEOLOJI"."ETUDAMAC" "Extent2" ON "Extent1"."ETUDAMACID" = "Extent2"."ID"
INNER JOIN "JEOLOJI"."ETUDTUR" "Extent3" ON "Extent1"."ETUDTURID" = "Extent3"."ID"
INNER JOIN "JEOLOJI"."FIRMA" "Extent4" ON "Extent1"."FIRMAID" = "Extent4"."ID"
INNER JOIN "JEOLOJI"."IL" "Extent5" ON "Extent1"."ILID" = "Extent5"."FEATUREID"
LEFT OUTER JOIN "JEOLOJI"."ILCE" "Extent6" ON "Extent1"."ILCEID" = "Extent6"."FEATUREID"
INNER JOIN "JEOLOJI"."DILIM" "Extent7" ON "Extent1"."DILIMID" = "Extent7"."ID"
INNER JOIN "JEOLOJI"."PLANTUR" "Extent8" ON "Extent1"."PLANTURID" = "Extent8"."ID"
WHERE ((1 = (CASE WHEN (( NVL(INSTR(LOWER(CASE WHEN ("Extent1"."ACIKLAMA" IS NULL) THEN '' ELSE "Extent1"."ACIKLAMA" END), LOWER('Ma')), 0) ) = 1) THEN 1 WHEN (( NVL(INSTR(LOWER(CASE WHEN ("Extent1"."ACIKLAMA" IS NULL) THEN '' ELSE "Extent1"."ACIKLAMA" END), LOWER('Ma')), 0) ) <> 1) THEN 0 END)) AND (22 <> "Extent1"."FIRMAID"))}
I solved the problem.
We are marking our string types in c# with StringLength attribute to prevent Entity Framework to create them as NCLOB columns on Oracle. Then Entity Framework generates columns with type nvarchar for c# propeties marked with StringLenth attribute.
In this query the where clause works fine with varchar2 because of the qoutes(as I learned from my Db profession friend.) So I changed the types of the columns and its solved.

If...Then...Else with multiple statements after Then

a very easy question: considering an If...Then...Else instruction in VBA, how can I separate multiple instructions after Then? In other words, should I write something like
If condition [ Then ]
[ statement1 ] & [statement2]
Else [Else statement] (i.e. using "&"),
or
If condition [ Then ]
[ statement1 ] And [statement2]
Else [Else statement] (i.e. using "And"),
or some other separator/command?
Multiple statements are to be separated by a new line:
If SkyIsBlue Then
StartEngines
Pollute
ElseIf SkyIsRed Then
StopAttack
Vent
ElseIf SkyIsYellow Then
If Sunset Then
Sleep
ElseIf Sunrise or IsMorning Then
Smoke
GetCoffee
Else
Error
End If
Else
Joke
Laugh
End If
This works with multiple statements:
if condition1 Then stmt1:stmt2 Else if condition2 Then stmt3:stmt4 Else stmt5:stmt6
Or you can split it over multiple lines:
if condition1 Then stmt1:stmt2
Else if condition2 Then stmt3:stmt4
Else stmt5:stmt6

Linq to SQL Case WHEN in VB.NET?

How do I do a Case WHEN in Linq to SQL (vb.net please).
In SQL it would be like this:
SELECT
CASE
WHEN condition THEN trueresult
[...n]
[ELSE elseresult]
END
How would I do this in Linq to SQL?
var data = from d in db.tb select new {
CaseResult = If (d.Col1 = “Case1”, "Case 1 Rised", If (d.Col1 = “Case2”, "Case 2 Rised", "Unknown Case"))
};
Check This Out
var data = from d in db.tb select new {
CaseResult = (
d.Col1 == “Case1” ? "Case 1 Rised" :
d.Col1 == “Case2” ? "Case 2 Rised" :
"Unknown Case")
};
Please Note that [ ? Symbol = then] , [ : Symbol = Or].
I haven't tried this but you may be able to do something like:
Dim query = From tbl In db.Table _
Select result =_
If(tbl.Col1 < tbl.Col2,"Less than",_
If(tbl.Col1 = tbl.Col2,"Equal to","Greater than"))
You would just need to keep nesting the If functions to handle all of your cases.
You can find more examples of various queries at http://msdn.microsoft.com/en-us/library/bb386913.aspx