Can't pinpoint error near the LIKE keyword - sql

I'm running into an error with a sql inquery near my LIKE statement. Am I formatting the LIKE clause incorrectly within the WHEN clause of a CASE? Here is the code.
SELECT
substring (Cases.FileNumber,4,6) AS [FileNumber]
,Charge.ChargeCode
,Cases.BookedLastName
,Cases.BookedFirstName
,Cases.ArrestDate
,Cases.BookedDOB
,Cases.BookedAge
,Charge.OffenseToDate
,Cases.BookedRace
,Cases.BookedSex
,Charge.OffenseStreetAddress1
,Charge.OffenseCity
,Charge.OffenseState
,Charge.OffenseZipCode
,Charge.ChargeDescription
,(SELECT CASE
WHEN charge1.ChargeDescription LIKE N'%heroin%' THEN 'Heroin'
ELSE 'Not Heroin'
END
FROM tblCsCharge AS charge1
INNER JOIN tblCsCases AS cases1
ON charge1.FileNumber = cases1.FileNumber
WHERE
charge1.BookedLastName = cases1.BookedLastName
AND charge1.BookedLastName = cases1.BookedLastName
AND charge1.BookedDOB = Cases.BookedDOB
AND cases2.ChargeCode IN (N'579.015-001Y201735')) AS HeroinYN
FROM
tblCsCases AS Cases
INNER JOIN tblCsCharge AS Charge
ON Cases.FileNumber = Charge.FileNumber
WHERE Cases.IssuedDate >= 01/01/2017
AND
Cases.IssuedDate <= #EndDate
AND
Charge.ChargeCode IN (N'579.015-001Y201735')
AND
Cases.BookedLastName NOT IN (N'Bogus')
ORDER By
Cases.BookedLastName
This is a sub-query within a bigger query focused on building a column that will simply output Heroin or Not Heroin based off of a large text field in our database.
EDITs:
Despite the changes that should make the code compile, the following error now occurs:
Invalid column name 'BookedLastName'.
Invalid column name 'BookedLastName'.
Invalid column name 'BookedDOB'.
The multi-part identifier "cases2.ChargeCode" could not be bound.

You have two errors in your code, both of which were pointed out, though not in the same answer.
Your case statement should be without the column name in parenthesis - I commented it out in the copy of your code below)
You're missing a closing parenthesis at the end of the query, right before the alias - I added it below.
.
,(SELECT CASE--(charge1.ChargeDescription)
WHEN charge1.ChargeDescription LIKE N'%heroin%' THEN 'Heroin'
ELSE 'Not Heroin'
END
FROM tblCsCharge AS charge1
INNER JOIN tblCsCases AS cases1
ON charge1.FileNumber = cases1.FileNumber
WHERE
charge1.BookedLastName = cases1.BookedLastName
AND charge1.BookedLastName = cases1.BookedLastName
AND charge1.BookedDOB = Cases.BookedDOB
AND cases2.ChargeCode IN (N'579.015-001Y201735')) AS HeroinYN

This seems to be the issue..
AND cases2.ChargeCode IN (N'579.015-001Y201735') AS HeroinYN
Since this is part of a sub-query, you need another parenthese
AND cases2.ChargeCode IN (N'579.015-001Y201735')) AS HeroinYN
ALSO
You can't put the column name after a CASE statement when you are using an equality operator.
This is acceptable
select
case columnName
when 'X' then 1
when 'Y' then 0
end
This is not
select
case columnName
when = 'X' then 1
when columnName like '%Y%' then 0
end
CORRECTED SCRIPT
,(SELECT CASE
WHEN charge1.ChargeDescription LIKE N'%heroin%' THEN 'Heroin'
ELSE 'Not Heroin'
END
FROM tblCsCharge AS charge1
INNER JOIN tblCsCases AS cases1
ON charge1.FileNumber = cases1.FileNumber
WHERE
charge1.BookedLastName = cases1.BookedLastName
AND charge1.BookedLastName = cases1.BookedLastName
AND charge1.BookedDOB = Cases.BookedDOB
AND cases2.ChargeCode IN (N'579.015-001Y201735')) AS HeroinYN

The proper syntax for that is:
CASE
WHEN charge1.ChargeDescription LIKE N'%heroin%' THEN 'Heroin'
ELSE 'Not Heroin'
END
Don't put the field name after CASE in this syntax.

Related

Postgres SQL state: 22P02 - invalid input syntax for integer

I'm using a sql query to export a database from my company's program.
Everything seems to be fine till I change the date on the "where" statement with a previous one.
Please find below the code:
SELECT p."Index", p."PSN" || CAST(p."PNR"as int) AS ID,
p."PSN" AS Serie, cast(p."PNR"as int) AS Numar,
pr."PINDate" AS r_gdate,
CASE WHEN pr."AsigEID"='10' THEN pr."PrimSUM" ELSE
pr."PrimSUM"*valuta1."EXCValue" END AS r_prima_lei,
CASE WHEN pr."AsigEID"='2'
THEN pr."PrimSUM"
ELSE CASE WHEN pr."AsigEID"='10' THEN pr."PrimSUM"/valuta2."EXCValue"
ELSE pr."PrimSUM"*valuta1."EXCValue"/valuta2."EXCValue"
END
END AS r_prima_eur,
CASE WHEN pr."AsigEID"='10' THEN pr."AsigSUM" ELSE
pr."AsigSUM"*valuta1."EXCValue" END as r_sa_lei,
CASE WHEN pr."AsigEID"='2'
THEN pr."AsigSUM"
ELSE CASE WHEN pr."AsigEID"='10' THEN pr."AsigSUM"/valuta2."EXCValue"
ELSE pr."AsigSUM"*valuta1."EXCValue"/valuta2."EXCValue"
END
END AS r_sa_eur,
pr."AsigStart", pr."AsigEnd", risc."Code", plink."Index"
FROM "PolsRisc" AS pr
LEFT JOIN "Pols" as p ON p."Index" = pr."PID"
LEFT JOIN "Riscs" as risc ON pr."RID" = risc."Index"
LEFT JOIN "PRLNK" plink ON plink."PTID" = p."PTID" AND plink."RID" = risc."Index"
LEFT JOIN "EXCValues" valuta1 ON valuta1."AtDate" = pr."AsigStart" AND valuta1."EID" = pr."AsigEID"
LEFT JOIN "EXCValues" valuta2 ON valuta2."AtDate" = pr."AsigStart" AND valuta2."EID"='2'
WHERE pr."PINDate" > '2020-08-01' AND pr."IsRezil" = 'false';
When I'm using '2020-08-01' the query works well. When I try to change it to a previous one eg. '2010-01-01' a get an error:
ERROR: invalid input syntax for integer: ""
SQL state: 22P02
I was looking for a solution on the previous posts but I didn't manage to solve this issue.
It looks like it is returning "" or a null value into one of the columns you are using integer logic for. The date change is just filtering out the data that would crash it.
You may need to use coalesce to reassign the nulls as 0 and then cast it back into being an int
select
cast(coalesce(table.column, 0) as int) as result
from table
I would advice to read the chapter http://www.postgresql.org/docs/current/interactive/sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS
. It's a brief and informative read.The cause for the error message is that '' is an empty string that has no representation in a numeric type like integer

Issue With SQL Pivot Function

I have a SQL query where I am trying to replace null results with zero. My code is producing an error
[1]: ORA-00923: FROM keyword not found where expected
I am using an Oracle Database.
Select service_sub_type_descr,
nvl('Single-occupancy',0) as 'Single-occupancy',
nvl('Multi-occupancy',0) as 'Multi-occupancy'
From
(select s.service_sub_type_descr as service_sub_type_descr, ch.claim_id,nvl(ci.item_paid_amt,0) as item_paid_amt
from table_1 ch, table_" ci, table_3 s, table_4 ppd
where ch.claim_id = ci.claim_id and ci.service_type_id = s.service_type_id
and ci.service_sub_type_id = s.service_sub_type_id and ch.policy_no = ppd.policy_no)
Pivot (
count(distinct claim_id), sum(item_paid_amt) as paid_amount For service_sub_type_descr IN ('Single-occupancy', 'Multi-occupancy')
)
This expression:
nvl('Single-occupancy',0) as 'Single-occupancy',
is using an Oracle bespoke function to say: If the value of the string Single-occupancy' is not null then return the number 0.
That logic doesn't really make sense. The string value is never null. And, the return value is sometimes a string and sometimes a number. This should generate a type-conversion error, because the first value cannot be converted to a number.
I think you intend:
coalesce("Single-occupancy", 0) as "Single-occupancy",
The double quotes are used to quote identifiers, so this refers to the column called Single-occupancy.
All that said, fix your data model. Don't have identifiers that need to be quoted. You might not have control in the source data but you definitely have control within your query:
coalesce("Single-occupancy", 0) as Single_occupancy,
EDIT:
Just write the query using conditional aggregation and proper JOINs:
select s.service_sub_type_descr, ch.claim_id,
sum(case when service_sub_type_descr = 'Single-occupancy' then item_paid_amt else 0 end) as single_occupancy,
sum(case when service_sub_type_descr = 'Multi-occupancy' then item_paid_amt else 0 end) as multi_occupancy
from table_1 ch join
table_" ci
on ch.claim_id = ci.claim_id join
table_3 s
on ci.service_type_id = s.service_type_id join
table_4 ppd
on ch.policy_no = ppd.policy_no
group by s.service_sub_type_descr, ch.claim_id;
Much simpler in my opinion.
for column aliases, you have to use double quotes !
don't use
as 'Single-occupancy'
but :
as "Single-occupancy",

isnull with AND : -An expression of non-boolean type specified in a context where a condition is expected, near 'and'

I am tryng to use isnull with AND operator
SELECT *
FROM contacts AS cont
LEFT JOIN contactphones AS contPhone
ON cont.contactid = contPhone.contactid
LEFT JOIN sys_phonetypedesc AS phont
ON phont.typeid = contPhone.phonetype
LEFT JOIN salutations AS tsal
ON tsal.salutid = cont.salutation
WHERE cont.contactid = '29'
AND ( Isnull(phont.typedesc, 1) )
AND ( Isnull(contPhone.phonenum, 1) )
ORDER BY phont.typedesc
but got following error
An expression of non-boolean type specified in a context where a
condition is expected, near 'and'.
I also tried using the case statement
SELECT *
FROM contacts AS cont
LEFT JOIN contactphones AS contphone
ON cont.contactid = contphone.contactid
LEFT JOIN sys_phonetypedesc AS phont
ON phont.typeid = contphone.phonetype
LEFT JOIN salutations AS tsal
ON tsal.salutid = cont.salutation
WHERE cont.contactid = '29'
AND (
CASE
WHEN phont.typedesc = NULL THEN 1
ELSE phont.typedesc
END as a)
but it is not working. I am looking for ifnull logic in MSSQL but case and if else not working correctly
please suggest
I don't think you need to use ISNULL() here, instead you are looking for IS NULL/IS NOT NULL. First let's see why you get this error message
An expression of non-boolean type specified in a context where a condition is expected, near 'and'.
You get this error because ( Isnull(phont.typedesc, 1) ) is not a boolean expression and that what the WHERE clause needs (True or False).
eg: Let's assume phont IS NULL, then ISNULL() will return 1, so you are writing cont.contactid = '29' AND 1 AND ....
What should I do then to get ride of this error?
Just make it a boolean expression as Isnull(phont.typedesc, 1) = 1 or what ever you want instead of =1, it maybe other too because it's not clear what you need to check.
Now, the use of ISNULL() as I seeis point less, cause the possible cases I can see is like the follow:
Isnull(phont.typedesc, 1) = 1 then directly phont IS NULL.
Isnull(phont.typedesc, 1) <> 1 then directly phont IS NOT NULL.
Isnull(phont.typedesc, 1) = AnyValue then why not directly phont = value or phont IN(<Values>) if you are looking for more than 1 value.
You're not comparing the result of isnull to anything in your where clause.
(isnull(phont.TypeDesc,1))
gives you either the TypeDesc, or if it's null gives you 1, but then you move directly onto an AND statement. In other words, if all relevant fields are null, what you'd be trying to do is:
where cont.ContactID = '29' and 1 and 1
You either have the isnull in the wrong place (if you want see it in your selected fields), or you forgot to compare it to something.
If you want to select rows where those fields are actually null then what you want is:
where cont.ContactID = '29'
and phont.TypeDesc is null
and contPhone.PhoneNum is null
select * from contacts as cont left join ContactPhones as contPhone on cont.ContactID=contPhone.ContactID
left join SYS_PhoneTypeDesc as phont on
phont.TypeID = contPhone.PhoneType
left join SALUTATIONS as tsal on tsal.salutid = cont.Salutation where cont.ContactID = '29' and (isnull(phont.TypeDesc,1))=check what u want here
and (isnull(contPhone.PhoneNum,1))=check what u want here enter code here
order by
phont.TypeDesc
Isnull(contPhone.phonenum,1) return 1 when your contPhone.phonenum value will be null else it will return that column value but the point is you got error because you have not used any comparison value as a result it thrown error
Your condition will be like below
Where contactId=29 and isnull(phonenum,1)= // any value

CASE WHEN SQL Syntax Error

I am attempting to us the CASE statement for the first time and I cannot understand why I am getting a syntax error on the last WHEN and ELSE. I am trying to extract a substring if a value starts with a specific set of characters. My Code is below:
SELECT
CASE
WHEN LEFT ([RCode],2) = 'BB' THEN SUBSTRING([RCode],3,LEN([RCode]))
WHEN LEFT ([RCode],4) = 'APT-' THEN SUBSTRING([RCode],5,LEN([RCode])
WHEN LEFT ([RCode],4) = 'PS-' THEN SUBSTRING([RCode],4,LEN([RCode])
ELSE [RCode]
END
FROM [Xperdyte].[dbo].[tJCLines]
Any guidance would be appreciated.
This won't (necessarily) fix your syntax problem, but I would recommend that you use like for the comparisons:
SELECT (CASE WHEN RCode LIKE 'BB%' THEN SUBSTRING([RCode], 3, LEN([RCode]))
WHEN RCode LIKE 'APT-%' THEN SUBSTRING([RCode], 5, LEN([RCode]))
WHEN RCode LIKE 'PS-%' THEN SUBSTRING([RCode], 4, LEN([RCode]))
ELSE [RCode]
END)
FROM [Xperdyte].[dbo].[tJCLines];
Then you don't have to count characters -- and the third condition will match.
Missed off two right parenthesis.
SELECT CASE WHEN LEFT([RCode],2) = 'BB'
THEN SUBSTRING([RCode],3,LEN([RCode]))
WHEN LEFT([RCode],4) = 'APT-'
THEN SUBSTRING([RCode],5,LEN([RCode]))
WHEN LEFT([RCode],4) = 'PS-'
THEN SUBSTRING([RCode],4,LEN([RCode]))
ELSE [RCode]
END
FROM [Xperdyte].[dbo].[tJCLines]

How to give change working of having function dynamicaly on executing an sql statement?

I'm having a Sql code like as follows
Select a.ItemCode, a.ItemDesc
From fn_BOM_Material_Master('A', #AsOnDate, #RptDate, #BranchID, #CompID)a
Left Outer Join fn_INV_AsOnDate_Stock(#StockDate, #AsOnDate, #RptDate, #BranchID, #CompID, #Finyear)b
On a.ItemCode=b.ItemCode and b.WarehouseCode<>'WAP'
and a.BranchID=b.BranchID and a.CompID=b.COmpID
Where a.ItemNatureCode = 'F' and a.BranchID = #BranchID and a.CompID = #CompID
Group by a.ItemCode, a.ItemDesc
Having sum(b.CBQty)<=0
Here the problem is that im passing an "#ShowZeroStock" value as as bit if the "#ShowZeroStock" value is '1' then Having should not be validated or (i.e: All values from the table should be returned including zero)
So How to change the query based on passed bit value "#ShowZeroStock"
I can Use "If else " condition at the top and remove having in else part, but for a lengthy query i can't do the same.
Is this the logic you want?
Having sum(b.CBQty) <= 0 or #ShowZeroStock = 1