Click here to Skip to main content
15,884,099 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello

i have a query than i want have conditional value in filter
i am nube in sql
please help me
this is my script:
SQL
DECLARE @InvCode NVARCHAR(20)
SET @InvCode = NULL

SELECT SD.* FROM [Accountting].[SaleInvoiceDetails] SD
	INNER JOIN [Accountting].[SaleInvoice] SI ON SD.[InvCode] = SI.[InvCode]
	WHERE SD.[InvCode] = (CASE WHEN @InvCode IS NULL THEN SD.[InvCode] ELSE @InvCode END)
	AND   CASE WHEN @InvCode IS NULL THEN SI.[Status] IN (1,2) ELSE SI.[Status] = SI.[Status] END

i want if invcode is null then filter status of SI table in 1,2 value and if InvCode is not null then does not filter anything so SI.[Status] = SI.[Status]

how can i implement?
help please
Posted
Updated 1-May-15 5:14am
v2

1 solution

You cannot use CASE like it was a control flow statement. It's a complex function that returns a value. You can then compare the value to something else. In your case it would be better to drop the CASE entirely and use simple AND/OR to specify the condition:
SQL
WHERE (@InvCode IS NULL OR SD.[InvCode] = @InvCode)
  AND (@InvCode IS NOT NULL OR SI.[Status] IN (1,2))

I believe this is much more readable than the CASE.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900