How do I execute different SELECT statements based on a CASE - sql

I am facing a problem in executing queries with CASE statement.
Based on my condition,(for eg. length), I want to execute different SQL statement.
Problematic sample query is as follows:
select case
when char_length('19480821') = 8
then select count(1) from Patient
when char_length('19480821')=10
then select count(1) from Doctor
end
Exception:
[Error] Script lines: 1-5 --------------------------
Incorrect syntax near the keyword 'select'.
Msg: 156, Level: 15, State: 2
Server: sunsrv4z7, Line: 2
I am not able to correct the syntax. I am getting the string for char_length as input from the user.
How can I fire queries based on certain condition?
Is CASE the right choice ? Or do I have to use any other thing.

Just put opening and closing bracket around select statement resolve you problem
select
case when
char_length('19480821')=8 then
(select count(1) from Patient )
when
char_length('19480821')=10 then
(select count(1) from Doctor )
end

select
case when char_length('19480821')=8 then (select count(1) from Patient)
when char_length('19480821')=10 then (select count(1) from Doctor)
end
The problem is that you are missing opening and closing brackets in your nested 'Select' statements :)

Please do note that it is not a case STATEMENT, it is a case EXPRESSION. By enclosing the queries in parentheses, you are converting them (syntactically) to values.
This is similar in principle to a subquery, such as
" select name from Doctor where salary = (select max(salary) from Doctor)"

select
case when
LEN('1948082100')=8 then
(select 'HELLO' )
when
LEN('194808210')=10 then
(select 'GOODBYE')
end
Change the values to test results.

Related

Issue using MINUS clause in SQL

While using minus clause in between two statements giving some error. Can someone help me with this?
Error is Msg 102, Level 15, State 1, Line 101
Incorrect syntax near 'MINUS'.
SELECT a from (SELECT DISTINCT(name) as a FROM hack WHERE name LIKE '%') a
MINUS
SELECT b from (SELECT DISTINCT(name) as b FROM hack WHERE name LIKE '[aeiou]%[aeiou]') b
MINUS is exist in Oracle. By seeing your error message, I hope you are looking in SQL Server.
In SQL Server, EXCEPT is the correct replacement for MINUS.
SELECT DISTINCT name
FROM hack
WHERE name LIKE '%'
EXCEPT
SELECT DISTINCT name
FROM hack
WHERE name LIKE '[aeiou]%[aeiou]'
You can simplify the logic to:
SELECT DISTINCT name
FROM hac
WHERE name NOT LIKE '[aeiou]%[aeiou]'
A simple comparison should be much more efficient that multiple comparisons along with set operators.

Sql - Error with expression of non-boolean

Can anyone help me find this issue?
This is my code
SELECT
MSC_Customer.cust_number, cust_name,
COUNT(ord_number) AS number_of_orders
FROM
MSC_Customer, MSC_Order
WHERE
MSC_Customer.cust_number = MSC_Order.cust_number
HAVING
MSC_Customer.cust_number
GROUP BY
cust_city LIKE 'Pennsylvania';
I get this error
Msg 4145, Level 15, State 1, Line 5
An expression of non-boolean type specified in a context where a condition is expected, near 'GROUP'.
I am trying to join the two tables, and use a COUNT aggregate and a GROUP BY clause in the SELECT statement
I'm going to suggest the following corrected query:
SELECT
c.cust_number,
c.cust_name,
COUNT(ord_number) AS number_of_orders
FROM MSC_Customer c
INNER JOIN MSC_Order o
ON c.MSC_Customer = o.cust_number
WHERE
cust_city LIKE '%Pennsylvania%' -- or maybe just cust_city = 'Pennsylvania'
GROUP BY
c.cust_number,
c.cust_name;
I am assuming that you want to aggregate by customer name/number. The check on the customer city would seem to belong in a WHERE clause, not in the GROUP BY clause. Of note, I rephrased your query to use an explicit inner join, instead of an old school implicit join. This is the preferred way of writing joins now.
Use condition in Where not Group By. Try below Script
SELECT MSC_Customer.cust_number, cust_name, count(ord_number) AS
number_of_orders
FROM MSC_Customer
JOIN MSC_Order ON
MSC_Customer.cust_number = MSC_Order.cust_number
WHERE cust_city like '%Pennsylvania%'
GROUP BY cust_city;
This type of error occurs generally when you write keyword which is used in expression or condition but you have not passed the value of the condition. For example -
select * from table where
this will give the same error as you have not passed here the value for where
You have missed to write the condition in having clause. You need to write the value with operator in having clause which may be one of the following.
HAVING
MSC_Customer.cust_number = '0120008024'
OR
HAVING
MSC_Customer.cust_number <> '0120008024'
OR
HAVING
MSC_Customer.cust_number like '%0120008024%'
You have to only specify the values in having clause you have missed as per your requirement.

QuerySyntaxException when using SQL EXCEPT and count(*)

I have a situation in Hibernate where I need to get the count(*) on a SQL EXCEPT query. Below is the query (imitated my original code):
String query = """
select count(*) as totalCount
from ( select distinct id from Employee
where name like '%Roger%
EXCEPT select distinct id from Manager ) Temporary
"""
Now, when I say:
hibernateSession.createQuery(query);
The below exception is thrown:
org.hibernate.hql.ast.QuerySyntaxException:
unexpected token: ( near line 1, column 36
My logs also show the below parsing errors when I catch the exception:
org.hibernate.hql.PARSER line 1:36: unexpected token: (
org.hibernate.hql.PARSER line 14:315: unexpected token: EXCEPT
org.hibernate.hql.PARSER line 15:68: unexpected token: from
I cannot avoid the count, WHERE or EXCEPT.
Because you're using hibernateSession.createQuery(query), hibernate is creating a query using HQL syntax, which doesn't work with your query, as you're using SQL syntax.
You most likely need to use something resembling hibernateSession.createSQLQuery(query).
For more on using native sql queries, see Native SQL in the Hibernate documentation.
The answers to this related question might also be useful.
Can you try this query instead? Replaced EXCEPT with NOT EXISTS.
String query = """
select count(*) as totalCount
from ( select distinct id from Employee as emp
where emp.name like '%Roger%
and not exists (
from Manager as m where emp.id = m.id
)
) Temporary
"""

Inserting or Updating a table with 2 sub queries in SQL Server

I am having a hard time doing a 'INSERT INTO' with 2 sub queries in the WHERE clause. I'm not sure wht I'm missing, it keep stating that an expression of non-boolean type specified in context where a condition is expected, near ';'.
This is my attempt at it:
INSERT INTO [Monitor].[dbo].[MonitorIncidents]
SELECT *
FROM dbo.MonitorSource
WHERE (
SELECT DISTINCT *
FROM Lookup.dbo.ServerInfo S
WHERE NOT EXISTS
(
SELECT 1
FROM Lookup.dbo.Facts F
WHERE F.FactsName = S.SrvName
AND W.DateTime > DATEADD(hour, -23, CURRENT_TIMESTAMP)
)
)
Your WHERE clause is missing an operand like =,<, >, etc. You are just returning a field to WHERE wihout a comparison. Depending on what you want to do, extend your WHERE to include a comparison.

SQL Select: Using CTE as dataset for IN clause - syntax error

While implementing this new idea Common Table Expressions in my query:
SELECT ..... FROM .... WHERE ... IN
(
;with CTEName as
(
CTE syntax goes here
)
SELECT .... FROM CTEName
)
GROUP BY ....
still getting the following query errors:
Msg 102, Level 15, State 1, Line 4
Incorrect syntax near ';'.
Msg 102, Level 15, State 1, Line 14
Incorrect syntax near ')'.
is this a valid usage of CTE?
Thanks.
WITH CTEName as
(
-- CTE syntax goes here
)
SELECT *
FROM mytable
WHERE myfield IN
(
SELECT ctefield
FROM CTEName
)
GROUP BY
myotherfield
In other words, the CTE should be defined before all other commands (as if they were actual tables).
Also note that the semicolon (;) is normally not required. However, the CTE syntax was implemented in SQL Server after it had already introduced the keyword WITH for its own purposes, so implicit statement breaking does not work with CTE anymore:
SELECT *
FROM mytable
WITH q AS (SELECT 1)
SELECT *
FROM q
It's hard to define where the WITH is used in the first or second statement here.
So it is considered a best practice to always prepend WITH with a semicolon so that you could easily cut and paste it anywhere in your code without having to worry about whether it is a first statement in a batch or not.