sql >> Base de Datos >  >> RDS >> Sqlserver

Usando SI EXISTE con un CTE

Desde MSDN

Se puede reescribir así

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

Aquí hay una demostración

;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)

Resultado: 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)

Resultado: OK