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

时间:2011-10-25 18:45:45

标签: sql isnull

我不知道这在SQL中是否可行,或者我是否必须编写存储过程但是我正在尝试使用下面的ISNULL函数,以便当参数@sku为null时我正在使用select声明将表格中的所有图表带回来:

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

3 个答案:

答案 0 :(得分:3)

使用OR

会更容易
WHERE
     (products.supplierCode in (@SupplierCode)) 
     AND 
     (products.sku like '%'+@SupplierCode+'%' OR @SupplierCode IS NULL)

这是你的意图,不是吗?

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

注意:

  • 领先的通配符无法优化,也不会使用索引。
  • 我假设您在@SupplierCode中没有此products.supplierCode in (@SupplierCode)
  • 的CSV

答案 1 :(得分:1)

不要过度复杂化。

制作WHERE条款:

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

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

答案 2 :(得分:0)

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 (@SupplierCode is null or products.sku like '%'+@SupplierCode+'%')
ORDER BY GooglePrice.idGooglePrice