sql如果参数为空字符串查询整个数据库else仅查询最近10天

kr98yfug  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(313)

我有一个关于过去10天的问题。我还声明了一个变量。如果变量是空字符串,我想查询过去10天(工作正常)。如果变量字符串不是空的,我想搜索所有的行,而不仅仅是最近10天。
我不能把if条件放在 WHERE 条款。我在想你有 GETDATE() 作为一个变量,如果字符串不为空,它将是sql中最早的日期,但不确定如何获取该日期。

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 + '%';
frebpwbc

frebpwbc1#

使用布尔逻辑:

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

这假设通过“empty”,您等于空字符串-这与您当前的查询一致,您所说的在参数为空时有效。如果你是说 null ,然后:

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

相关问题