zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

sql query if parameter is null select all

SQL is if SELECT null all Query Parameter
2023-09-11 14:14:17 时间

sql query if parameter is null select all

Try this:

SELECT * 
FROM MY_TABLE 
WHERE @parameter IS NULL OR NAME = @parameter;

 

 

SQL select all if parameter is null else return specific item

回答1

Use case statement:

SELECT ProductID, ProductName,ProductDesc 
FROM product 
WHERE ProductID = CASE WHEN @productID IS NULL THEN ProductID ELSE @productID END

Or IIF() function if you’re using SQL Server 2012:

SELECT ProductID, ProductName,ProductDesc 
FROM product 
WHERE ProductID =IIF(@productID IS NULL, ProductID, @productID )

 

回答2

Why not just:

DECLARE @productID INT = NULL

SELECT ProductID, ProductName,ProductDesc 
FROM   product 
WHERE  ProductID = @productID
OR     @productID IS NULL;

Here a demo in SQLFiddle with NULL and a value for @productID