Answered Any alternative query?

  • Wednesday, March 06, 2013 1:41 PM
     
      Has Code

    Is there any alternative query for the following code for better performance..??

    declare @id int = 1
    
    select id from temp
    	where @id = 1 or visitid =@id
    
    
    
    select id from temp
    	where id = case when @id = 1 then id
    	else @id
    	end


    Please remember to mark the replies as answers if they help. - Kerobin

All Replies

  • Wednesday, March 06, 2013 1:48 PM
     
     Answered Has Code

    Hello Kerobin,

      you can try some thing as below if you dont want to achieve in single SQL statement. also adding an index to id column will imporve the performance

    if @id = 1
    begin
    select id from temp
    end
    else
    begin
    select id from temp
    where id = @id
    end


    Best Regards Sorna

  • Wednesday, March 06, 2013 2:34 PM
     
     Answered Has Code

    Another way that may help

    declare @id int = 1
    
    select id from temp
    	where @id = 1 or visitid =@id Option(Recompile)

    Before using that technique, make sure you have SP2 if you are on SQL Server 2008.  If you are on SQL Server 2008R2, you need SP1.  If you are on Sql Server 2012 or later, you will be fine.  Do not use this technique on SQL 2005 or earlier, or any earlier version of SQL 2008 or 2008R2.

    Tom