简体   繁体   中英

SQL If statement - check if row count of subquery = 1

Any suggestions on how to do this? I have a complex if statement in a query that needs to check on various conditions for a given table. EG:

IF EXISTS  (SELECT Labeler
  FROM [xx].[dbo].[manuf]
  where Lname like '@Lname' AND Approved = 0 AND Access = 'P')
      
  AND NOT EXISTS (SELECT Labeler
  FROM [xx].[dbo].[manuf]
  where Lname like '@Lname' AND Approved = 1)

  AND NOT EXISTS(SELECT Labeler
  FROM [xx].[dbo].[manuf]
  where Lname like '@Lname' AND Approved = 2)


    RETURN 1
ELSE...

However, for that first subquery, I also need to make sure it only yields one row. Exists just checks for 1 or more rows, but how do I constrain it to only return 1 if that first subquery has ONLY one row?

If you specifically need exactly one row, you can use aggregation:

IF 1 = (SELECT COUNT(*)
        FROM [xx].[dbo].[manuf]
        WHERE Lname like '@Lname' AND Approved = 0 AND Access = 'P'
       ) AND . . .

I strongly recommend EXISTS when you just need to check existence, because it is faster than aggregation.

This query can be simplified to access the [xx].[dbo].[manuf] table only once:

IF 1 = (
  select 1
  from [xx].[dbo].[manuf]
  where Lname like '@Lname'
    and Approved in (0, 1, 2)
  having
    /*There's only one row, that is approved = 0 and access = 'P'*/
    sum(case when Approved = 0 and Access = 'P' then 1 end) = 1
    /*And there's no rows with Approved > 0*/
    and max(Approved) = 0
)

  RETURN 1
...

db<>fiddle is here .

I would use ROW_NUMBER() :

SELECT ROW_NUMBER(PARTITION BY Labeler ORDER BY x)
FROM [xx].[dbo].[manuf]
where Lname like '@Lname' AND Approved = 0 AND Access = 'P'

Then check to see if ROW_NUMBER()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM