ISNULL,SQL,使用select语句作为第二个参数

ISNULL,SQL,使用select语句作为第二个参数,sql,isnull,Sql,Isnull,我不知道这在SQL中是否可行,或者我是否必须编写一个存储过程,但我正在尝试使用ISNULL函数,如下所示,以便当参数@sku为null时,我使用select语句返回表中的所有sku: SELECT GooglePrice.idGooglePrice, GooglePrice.idProduct, products.sku, products.wholeprice, products.price as CurrentHMMPrice, GooglePrice.bestPrice, Goo

我不知道这在SQL中是否可行,或者我是否必须编写一个存储过程,但我正在尝试使用ISNULL函数,如下所示,以便当参数@sku为null时,我使用select语句返回表中的所有sku:

SELECT     GooglePrice.idGooglePrice, GooglePrice.idProduct,  products.sku, products.wholeprice, products.price as CurrentHMMPrice, GooglePrice.bestPrice, GooglePrice.link, GooglePrice.title, GooglePrice.description, GooglePrice.ourPrice as PriceCompHMMPrice, 
                      GooglePrice.searchType, GooglePrice.shippingCost, GooglePrice.cheapestOrder, GooglePrice.timeStamp, 
    'ShippingCostNew' = CASE
        WHEN GooglePrice.shippingCost = -1 THEN 'N/A'
        WHEN GooglePrice.shippingCost = 0 THEN 'Free Shipping'
        WHEN GooglePrice.shippingCost > 0 Then cast(GooglePrice.shippingCost as varchar)
        END
FROM         GooglePrice INNER JOIN
                      products ON GooglePrice.idProduct = products.idProduct
WHERE     (products.supplierCode in (@SupplierCode)) AND ISNULL((products.sku like '%'+@sku+'%'), (products.sku in (select sku from products where products.sku)))

ORDER BY GooglePrice.idGooglePrice

不要把它复杂化

使您的
WHERE
子句:

WHERE     
   ((products.supplierCode in (@SupplierCode)
       AND 
   (products.sku like '%'+@SupplierCode+'%'))
OR (@suppliercode IS NULL)

你没有真正解释你的逻辑,所以我猜,但想法是对
NULL
比较进行单独检查。

不要过度复杂化它

使您的
WHERE
子句:

WHERE     
   ((products.supplierCode in (@SupplierCode)
       AND 
   (products.sku like '%'+@SupplierCode+'%'))
OR (@suppliercode IS NULL)

你没有真正解释你的逻辑,所以我猜,但想法是对
NULL
比较进行单独检查。

使用OR会更容易些

WHERE
     (products.supplierCode in (@SupplierCode)) 
     AND 
     (products.sku like '%'+@SupplierCode+'%' OR @SupplierCode IS NULL)
这是你的意图,不是吗

     AND 
     products.sku like ISNULL('%'+@SupplierCode+'%',products.sku)
注:

  • 无法优化前导通配符,并且不会使用索引
  • 我假设您在@SupplierCode中没有此
    产品的CSV。SupplierCode在(@SupplierCode)

    • 使用OR会更容易

      WHERE
           (products.supplierCode in (@SupplierCode)) 
           AND 
           (products.sku like '%'+@SupplierCode+'%' OR @SupplierCode IS NULL)
      
      这是你的意图,不是吗

           AND 
           products.sku like ISNULL('%'+@SupplierCode+'%',products.sku)
      
      注:

      • 无法优化前导通配符,并且不会使用索引
      • 我假设您在@SupplierCode中没有此
        产品的CSV。SupplierCode在(@SupplierCode)

      如果此参数为null,我希望带回所有sku。如果此参数为null,我希望带回所有sku。