我有一个简单的声明:
SELECT * FROM Articles WHERE Category = @category
我需要当@category为0或null时,WHERE条件被忽略并且SQL选择所有文章; 类似于以下声明:
SELECT * FROM Articles
IF @category = 0
BEGIN
WHERE Category = @category
END
所以我会这样构造它
IF @category = 0
BEGIN
SELECT * FROM Articles WHERE Category = @category
END
编辑:
您也可以这样使用 case 语句:
select * from Articles where category = (
CASE WHEN @category= 0 THEN @category END)