简体   繁体   中英

SQL Query with condition in where clause

I have written a sql query like,

DECLARE @TypeID BIGINT

--SET @TypeID=169

SELECT TypeID from TrnChecklist where TypeID IN 
(CASE WHEN (@TypeID IS NOT NULL AND @TypeID <> '') THEN @TypeID 
ELSE (select distinct TypeID from TrnChecklist where AuditID=57) END)

If I provide @TypeID it gives me records. But If I do not provide @TypeID then it gives me error

"Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=,......"

But I am using "TypeID IN " in where condition since "select distinct TypeID from TrnChecklist where AuditID=57" returns more than one value

My data sample (in TrnChecklist table. Few other columns but i am using only these 2)

在此处输入图片说明

CASE expression evaluates a list of conditions and returns one of multiple possible result expressions.

It does not work because you are returning multiple values per evaluation in a CASE expression which is expected to return a scalar value per evaluation.

If you put case over table data, it evaluates each row to return a value per row .

You can use this query here

SELECT TypeID FROM TrnChecklist WHERE TypeID IN 
(SELECT TypeID FROM TrnChecklist 
WHERE AuditID=57 AND (@TypeID IS NULL OR @TypeID = '') 
UNION SELECT @TypeID)

I Trying to use a case expression inside IN() is not likely to work. Try to use boolean logic. You want the nominated value by parameter, or you want an IN() list match.

DECLARE @TypeID bigint

--SET @TypeID=169

SELECT
  TypeID
FROM TrnChecklist
WHERE (TypeID = @TypeID AND @TypeID IS NOT NULL AND @TypeID <> '') 
OR ( NOT  (TypeID = @TypeID AND @TypeID IS NOT NULL AND @TypeID <> '') 
    AND TypeID IN  (SELECT DTypeID
                    FROM TrnChecklist
                    WHERE AuditID = 57)
   )

There may be a few conditions that can still be removed from the query above but I think it would work.

Note, I have removed distinct. Often the cost of distinct is greater than the size of the in list. Put it back if really needed.

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