Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSql Case within Case

I am trying to do a select statment in tsql with a case within a case. First is based on what the SearchField is. Next I need to do it based on the SearchOper.

    declare @searchField varchar(50)  
    declare @searchString varchar(50)
    declare @searchOper varchar(50)

    case @searchField
     when 'CompanyName' then
        case @searchOper
          when 'eq' then
            select * from tbl1 where CompanyName = @searchString
         when 'ne' then 
           select * from tbl1 where CompanyName <> @searchString
         end
     when 'StoreNum' then
        case @searchOper
          when 'eq' then
             select * from tbl1 where StoreNum = @searchString
          when  'ne' then
             select * from tbl1 where StoreNum <> @searchString
        end 
     end 

Note what I am trying to do is within the case statement do a select.

I get a message saying Incorrect syntax near the keyword 'case'.

like image 439
Nate Pet Avatar asked May 28 '26 10:05

Nate Pet


1 Answers

Based on your example, you probably want to use IF statements (here is an example with ELSE, but you can use IF and ELSE IF multiple times too):

declare @searchField varchar(50)  
declare @searchString varchar(50)
declare @searchOper varchar(50)

IF @searchField='CompanyName'
BEGIN
    IF @searchOper='eq'
    BEGIN
        select * from tbl1 where CompanyName = @searchString
    END
    ELSE
    BEGIN
        select * from tbl1 where CompanyName <> @searchString
    END
END
ELSE 
BEGIN
    IF @searchOper='eq'
    BEGIN
        select * from tbl1 where StoreNum = @searchString
    END
    ELSE
        select * from tbl1 where StoreNum <> @searchString
    END
END

CASE is very similar, but is rather used with inline statements (i.e. SELECT CASE 1=1 THEN 'a' ELSE 'b' END).

like image 50
Ilya Avatar answered May 31 '26 05:05

Ilya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!