0

I have a SQL Server query that filters some data using:

and datepart(mm,cs.timestamp) <= @month

I have a parameter @accumulate that if true then I want to to above logic but if false then I want to do:

and datepart(mm,cs.timestamp) = @month

Any clue on how to that in same line?

3
  • Can you show all of the code? You might be better off using dynamic SQL. Commented Jan 20, 2017 at 20:42
  • Similar question to consider: stackoverflow.com/questions/2568775/… Commented Jan 20, 2017 at 20:46
  • Not an answer to your question, more of a comment on coding style. sqlblog.org/2011/09/20/… Commented Jan 20, 2017 at 21:47

3 Answers 3

3

I'm not sure if you can do it in one line. But you could do it in multiple lines like:

and ( ( datepart(mm,cs.timestamp) <= @month and @accumulate = true )
   or ( datepart(mm.cs.timestamp) = @month and @accummulate = false ) )
Sign up to request clarification or add additional context in comments.

Comments

0

This is a little more concise, that could be one line

(DATEPART(mm,cs.timestamp) = @month 
 OR (@accumulate = 1 AND DATEPART(mm, cs.timestamp) < @month))

or, with a nod to Sean's comment (which is good advice)

(DATEPART(MONTH,cs.timestamp) = @month 
 OR (@accumulate = 1 AND DATEPART(MONTH, cs.timestamp) < @month))

or, if you want a short but opaque and nasty bit of code (and @accumulate is a bit)

SIGN(@month - DATEPART(MONTH, cs.timestamp)) in (0, @accumulate)

Comments

0

You should use stored procedure with IF and THEN statement to separate the two conditions

Comments

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.