tags:

views:

181

answers:

2

How can I filter columns in where condition based on valued passed.

Ex:

declare @number nvarchar(200)
set @number = '2ddafa3'

Here @number could be int or uniqueIdentifer

so in where clause how can i achieve something as below.

select * from IntegrationIDTransactions
where case ISNUMERIC(@number) 
      When 1  Then [TransactioniD] = @number
      else [TransactionDomainGuid] = @number

Thanks

+2  A: 

This should work:

where @number = 
    case ISNUMERIC(@number) 
        when 1 then cast([TransactioniD] as varchar(200))
        else cast([TransactionDomainGuid] as varchar(200))
    end

Edited to add the cast. The cast has to be inside the CASE; SQL server requires that all paths of the case produce the same variable type.

Andomar
Thanks Andomar.
Nev_Rahd
Sorry still getting error: Msg 206, Level 16, State 2, Line 4Operand type clash: uniqueidentifier is incompatible with intTried with:declare @number nvarchar(200)set @number = '5'select * from IntegrationIDTransactionswhere @number = case ISNUMERIC(@number) when 1 Then [TransactioniD] else [TransactionDomainGuid] end
Nev_Rahd
Right, it takes the type of the first CASE branch and assumes all branches produce that type. Edited the answer. Remus Rusanu's answer would perform better by the way.
Andomar
Thanks again Andomar.
Nev_Rahd
+1  A: 

You should avoid such constructs and instead have two queries, one for WHERE TransactionId and one for WHERE TransactionDomainGuid:

if ISNUMERIC(@number)
  select * from IntegrationIDTransactions
  where [TransactioniD] = @number
else 
  select * from IntegrationIDTransactions
  else [TransactionDomainGuid] = @number

Even better, have the client do the IF and call the appropriate query. Writing queries like the one in your example is a performance killer, the result is unsargable and creates usually the worst execution plan for both cases.

Remus Rusanu
+1, this is the only correct approach here if performance is of any concern.
Dane