Skip to content
Advertisement

SQL if parameter is empty string query entire DB else query only last 10 days

I have a query for the last 10 days. I also have a variable declared. If the variable is empty string I want to query the last 10 days (works fine). If the variable string is not empty I want to search all rows not just the last 10 days.

I cannot put an if condition around the WHERE clause. I was thinking have GETDATE() as a variable and if the string is not empty it would be the oldest date in SQL but not sure how to get that date.

Advertisement

Answer

Use boolean logic:

This assumes that by “empty”, you equal to the empty string – which is consistent with your current query, which you said works when the parameter is empty. If you mean null, then:

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement