1

I have this Stored Procedure, where i need to check if @DateChk == 1, THEN i want to add a WHERE-clause to the SQL statement in the SP. If its 0, there should not be any WHERE-clause.

How do i script such function? In a program i could just build in the string to pass to the server, but i have not found any way to do this in the SQL server.

SELECT  dateDay, SUM(nok) as NOK, SUM(ok) as OK,  (SUM(ok) + SUM(nok)) as 'Total'
FROM #st
SELECT CASE @DateChk
WHEN 1: WHERE dateDay BETWEEN '2016-08-01' AND '2016-08-31'

Something like this, if @DateChk = 1, the WHERE should be added, else fetch all records.

1 Answer 1

3

You can modify your condition like this:

SELECT  dateDay, SUM(nok) as NOK, SUM(ok) as OK,  (SUM(ok) + SUM(nok)) as 'Total'
FROM #st
WHERE 
(@DateChk = 1 and (dateDay BETWEEN '2016-08-01' AND '2016-08-31'))
or @DateChk = 0

And it will exactly match your desired behaviour: condition on dateDay will be applied only when @DateChk = 1.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, this helped tremendous.
Another question. if i have 2 more BITs i want to do IF on? if the DateChk = 0, but ArtNrChk is 1, or if both are 1 etc? I currently have 4 checkboxes to select what to display/filter on.
@StefanGrönberg then same logic can be applied. Just modify your where condition according to new logic, like "((some_condition) and (additional condition to apply)) or (negation of some_condition)"
Right, thanks once again @Andy Korneyev. Starting to get hand of this and-oring, and it works nicely now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.