Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using IF EXISTS with a CTE

Tags:

sql

sql-server

I want to check if a CTE table has record or null. But I always get error message 'Incorrect syntax near the keyword 'IF'' for the SQL below. Now there is no matching record in ADMISSION_OUTSIDE TABLE. The result of the SQl should print 'NOT OK'. Thanks,

WITH ADMISSION_OUTSIDE AS 
(   .....
.....
)

IF EXISTS (SELECT * FROM ADMISSION_OUTSIDE)
PRINT 'OK'
ELSE PRINT 'NOT OK'
like image 722
Ice Avatar asked Sep 19 '16 15:09

Ice


People also ask

Can I use an IF statement in a CTE?

An IF is a control flow mechanic that separates statements (or blocks of statements) so you can't declare a CTE and conditionally refer to it on multiple statements.

Which clause Cannot be used in CTE?

The clauses like ORDER BY, INTO, OPTION clause with query hints, FOR XML, FOR BROWSE, cannot be used in the CTE query definition. "SELECT DISTINCT", GROUP BY, PIVOT, HAVING, Scalar aggregation, TOP, LEFT, RIGHT, OUTER JOIN, and Subqueries are not allowed in the CTE query definition of a recursive member.

Can we use exists in subquery?

The EXISTS operator is used to test for the existence of any record in a subquery. The EXISTS operator returns TRUE if the subquery returns one or more records.

Can a CTE have a subquery?

A CTE (common table expression) is a named subquery defined in a WITH clause. You can think of the CTE as a temporary view for use in the statement that defines the CTE. The CTE defines the temporary view's name, an optional list of column names, and a query expression (i.e. a SELECT statement).


1 Answers

From MSDN

A CTE must be followed by a single SELECT, INSERT, UPDATE, or DELETE statement that references some or all the CTE columns

It can be re-written like this

WITH ADMISSION_OUTSIDE AS 
(   .....
.....
)
SELECT 'OK' WHERE EXISTS (SELECT * FROM ADMISSION_OUTSIDE)
UNION ALL
SELECT 'NOT OK' WHERE NOT EXISTS (SELECT * FROM ADMISSION_OUTSIDE)

Here is a demo

;WITH CTE AS
(
SELECT 1 as a WHERE 1=0
)
SELECT 'OK' WHERE EXISTS (SELECT * FROM CTE)
UNION ALL
SELECT 'NOT OK' WHERE NOT EXISTS (SELECT * FROM CTE)

Result : NOT OK

;WITH CTE AS
(
SELECT 1 as a WHERE 1=1
)
SELECT 'OK' WHERE EXISTS (SELECT * FROM CTE)
UNION ALL
SELECT 'NOT OK' WHERE NOT EXISTS (SELECT * FROM CTE)

Result : OK

like image 120
Pரதீப் Avatar answered Oct 30 '22 21:10

Pரதீப்