如何在“ WHERE IN(')”语句中使用通配符

时间:2019-02-18 11:58:10

标签: sql sql-server where sql-in

我有一个WHERE IN ('')语句,如果未输入任何内容,如何选择全部?

2 个答案:

答案 0 :(得分:2)

取决于您正在使用的数据库。但是您可以执行以下操作:

-- SQLServer
DECLARE @in varchar(20) = ''
SELECT * FROM <table> WHERE (@in = '' or <field> IN (''))

-- OR
IF @in = '' 
    SELECT * FROM <table>
ELSE
    SELECT * FROM <table> WHERE <field> IN ('')

答案 1 :(得分:0)

如果要选择所有值,如果变量没有值,则只需使用ISNULL函数(将进行索引扫描):

WHERE yourField IN (ISNULL(@yourNullVariable, yourField))

让我展示一个例子:

DECLARE @table TABLE
(
    FooDate DATETIME,
    FooBar VARCHAR(50) 
)

INSERT INTO @table
(
    FooDate,
    FooBar
)
VALUES
(   GETDATE(), -- FooDate - datetime
    'A'         -- FooBar - varchar(50)
    )
, ('2019-02-18', 'AA')
, ('2019-01-18', 'B')
, ('2019-01-18', 'BB')

DECLARE @fooVariable VARCHAR(50) = NULL
SELECT * FROM @table tbl
WHERE  tbl.FooBar = ISNULL(@fooVariable, tbl.FooBar)

输出:

FooDate                    FooBar
2019-02-18 16:37:20.920      A
2019-02-18 00:00:00.000      AA
2019-01-18 00:00:00.000      B
2019-01-18 00:00:00.000      BB

或使用动态SQL(将具有索引查找):

DECLARE @fooVariable VARCHAR(50) = NULL
DECLARE @sql NVARCHAR(max), @where NVARCHAR(255);

SET @sql = N'SELECT * FROM Yourtable tbl'
IF @fooVariable IS NOT NULL
    BEGIN 
        SET @where = ' tbl.FooBar = ' + @fooVariable
        SET @sql = CONCAT(@sql, @where)
    END


EXEC SP_EXECUTESQL @SQL