Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 如果参数为null,则SQL全选,否则返回特定项_Sql Server - Fatal编程技术网

Sql server 如果参数为null,则SQL全选,否则返回特定项

Sql server 如果参数为null,则SQL全选,否则返回特定项,sql-server,Sql Server,是否有方法编写以下脚本,以便在ProductID变量为null时返回所有产品?并在产品不为空时返回特定产品。 到目前为止,我所拥有的: DECLARE @productID INT = NULL SELECT ProductID, ProductName, ProductDesc FROM product WHERE ProductID = @productID 用例声明: SELECT ProductID, ProductName,Product

是否有方法编写以下脚本,以便在ProductID变量为null时返回所有产品?并在产品不为空时返回特定产品。 到目前为止,我所拥有的:

DECLARE @productID INT = NULL

SELECT
    ProductID,
    ProductName,
    ProductDesc 
FROM
    product 
WHERE
    ProductID = @productID
用例声明:

SELECT ProductID, ProductName,ProductDesc 
FROM product 
WHERE ProductID = CASE WHEN @productID IS NULL THEN ProductID ELSE @productID END
SELECT ProductID, ProductName,ProductDesc 
FROM product 
WHERE ProductID = CASE WHEN @productID IS NULL THEN ProductID ELSE @productID END
或IIF()函数,如果您使用的是SQL Server 2012:

SELECT ProductID, ProductName,ProductDesc 
FROM product 
WHERE ProductID =IIF(@productID IS NULL, ProductID, @productID )
为什么不只是:

DECLARE @productID INT = NULL

SELECT ProductID, ProductName,ProductDesc 
FROM   product 
WHERE  ProductID = @productID
OR     @productID IS NULL;
这里有一个空值和@productID的值

DECLARE @productID INT = NULL

SELECT 
    ProductID,
    ProductName,
    ProductDesc 
FROM
    product 
WHERE 
    ProductID = isnull(@productID,ProductID)
由于“”未被识别为
NULL
I使用了值

SELECT ProductID, ProductName,ProductDesc 
FROM product 
WHERE ProductID =IIF(@productID =1, ProductID, @productID )
在我的代码中:

 MyDataAdapter.SelectCommand.Parameters("@productID").Value = 1

使用
CASE
语句时,性能会有惊人的提高:

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

ISNULL()。例如,如果希望在
@productId为NULL时使用一系列值,则可以执行
操作,其中productId=@productId或(@productId为NULL,productId介于@Min和@Max之间)