Question

I have the following query:

DECLARE @MyTable TABLE
    (
      [ID] INT ,
      [Col1] INT ,
      [Col2] INT
    )



INSERT  INTO @MyTable
        SELECT  1 ,
                2 ,
                1
        UNION
        SELECT  1 ,
                2 ,
                3
        UNION
        SELECT  2 ,
                2 ,
                3
        UNION
        SELECT  2 ,
                2 ,
                3
        UNION
        SELECT  3 ,
                2 ,
                3
        UNION
        SELECT  3 ,
                2 ,
                1 



DECLARE @ID INT 

SET @ID = 1

SELECT  *
FROM    @MyTable
WHERE   ( Col1 = ( CASE WHEN [ID] = @ID THEN 2
                   END )
          OR [Col2] = ( CASE WHEN [ID] != @ID THEN 1
                        END )
        )

WHEN [ID] = @ID I want to match Col1 with constant value equals to 2 and when [ID] != @ID I want to match Col2 with constant value equals to 1. Can the above query be improve so that [ID] equality check can be done only once in the above query, something like this:

SELECT  *
FROM    @MyTable
WHERE  
if([ID] = @ID)
Col1=2
ELSE
[Col2]=1
Was it helpful?

Solution

Is this the logic that you want?

where id = @id and col1 = 2 or
      id <> @id and col2 = 1

I don't know why you are concerned about the performance of such a clause. You can do what you want with a case statement:

where 1 = (case when id = @id
                then (case when col1 = 2 then 1 end)
                else col2 = 1
           end)

But this is a needless "optimization". It is not even clear that the nested case statements would be any faster than the first version. Such simple operations are really, really fast on modern computers. And, what slows databases down is the processing of large volumes of data (in general), not such simple operations.

OTHER TIPS

Perhaps just:

Select  *
From    @MyTable
Where   ((id = @id and col1 = 2) or (id <> @id and col2 = 1))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top