patternsqlModerate
Using a CTE in IF EXISTS Query
Viewed 0 times
querycteusingexists
Problem
Is it possible to do something similar to the following in SQL Server 2012?
I tried using this syntax and received an error. If this is not possible, would using a temp table be the best way to accomplish this?
IF EXISTS (
WITH DATA AS (
SELECT *,
ROW_NUMBER() OVER(PARTITION BY column ORDER BY Column) AS rn
FROM table )
SELECT *
FROM DATA
WHERE rn = 2 )
BEGIN
...
ENDI tried using this syntax and received an error. If this is not possible, would using a temp table be the best way to accomplish this?
Solution
A CTE can't be used as a subquery. One workaround would be:
Another would be:
Even if your proposed syntax were valid, the
IF EXISTS
(
SELECT 1 FROM
(
SELECT ROW_NUMBER() OVER(PARTITION BY column ORDER BY Column) AS rn
FROM table
) AS DATA
WHERE rn = 2
)
BEGIN
...
ENDAnother would be:
IF EXISTS (SELECT 1 FROM dbo.table GROUP BY column HAVING COUNT(*) > 1)
BEGIN
...
ENDEven if your proposed syntax were valid, the
EXISTS wouldn't short circuit in that case anyway, I would think (and I suspect that is why you'd want to use it), since the window function must materialize over the full set before rn could be filtered.Code Snippets
IF EXISTS
(
SELECT 1 FROM
(
SELECT ROW_NUMBER() OVER(PARTITION BY column ORDER BY Column) AS rn
FROM table
) AS DATA
WHERE rn = 2
)
BEGIN
...
ENDIF EXISTS (SELECT 1 FROM dbo.table GROUP BY column HAVING COUNT(*) > 1)
BEGIN
...
ENDContext
StackExchange Database Administrators Q#99072, answer score: 10
Revisions (0)
No revisions yet.