簡體   English   中英

SQL If 語句 - 檢查子查詢的行數是否 = 1

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

關於如何做到這一點的任何建議? 我在查詢中有一個復雜的 if 語句,需要檢查給定表的各種條件。 例如:

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...

但是,對於第一個子查詢,我還需要確保它只產生一行。 Exists 僅檢查 1 行或更多行,但是如果第一個子查詢只有一行,我如何將其限制為僅返回 1?

如果您特別需要一行,則可以使用聚合:

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

當您只需要檢查存在性時,我強烈推薦EXISTS ,因為它比聚合更快。

此查詢可以簡化為僅訪問[xx].[dbo].[manuf]表一次:

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 在這里

我會使用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'

然后檢查是否ROW_NUMBER()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM