0

I'm creating a simple query, a simple select like select x,y,z from etc etc but in the software, there are start date and end date.

If the user fills in only the first date, then it will use a where clause like this:

where....
and...
and x.date >= Startdate

If the user fills in both dates, it will use:

where....
    and...
    and x.date between @Startdate and @enddate

If the user fills in only end date:

 where....
    and...
    and x.date < @enddate

I'm getting a syntax error with everything I'm trying to do.

 where....
        and...
        case when @startdate is not null and @enddate is null
           and x.date >= Startdate

Or even using if. What is the correct syntax for this? Or this is something programmers need to fix inside the software's code?

2

Try like this

WHERE....
AND...
AND (x.DATE>= @Startdate OR @Startdate IS NULL)
AND (x.DATE<= @enddate OR @enddate IS NULL)

Possibly with OPTION (RECOMPILE).

See Dynamic Search Conditions in T‑SQL by Erland Sommarskog.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.