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.

DECLARE @searchString VARCHAR(50) = '';

SELECT
    [filterFileName], 
    event_filter.tradingDate, 
    log_folder.logFolderID, 
    isVMonDagLocked, 
    de_file.importStatus as de_importStatus,
    de_file.isValid as de_isValid,    
FROM [TradingCenter].[Trade].[TradingEventFilterFile] as event_filter
LEFT JOIN [TradingCenter].[Trade].[TradingEventFilterFile2LogFolder] as log_folder /*Get relation rows for filterfile*/
    ON event_filter.filterFileID = log_folder.filterFileID
LEFT JOIN [TradingCenter].[Trade].[TradingEventLogFolder] as trade_event_log_folder /**/
    ON log_folder.logFolderID = trade_event_log_folder.logFolderID
LEFT JOIN [TradeLog].[Trade].[DEFile] as de_file /*join DE file*/
    ON trade_event_log_folder.logFolderID = de_file.logFolderID
WHERE event_filter.createdOn >= DATEADD(day, -10, GETDATE())
    AND event_filter.filterFileName LIKE '%' + @searchString + '%';

Advertisement

Answer

Use boolean logic:

WHERE 
    (
        @searchString = ''
        AND event_filter.createdOn >= DATEADD(day, -10, GETDATE())
    )
    OR (
        @searchString <> ''
        AND event_filter.filterFileName LIKE '%' + @searchString + '%'
    )

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:

WHERE 
    (
        @searchString IS NULL
        AND event_filter.createdOn >= DATEADD(day, -10, GETDATE())
    )
    OR (
        @searchString IS NOT NULL
        AND event_filter.filterFileName LIKE '%' + @searchString + '%'
    )
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement