我正在寻找的是,如果我选择停产,priceunit等,它会在where子句中向我显示该部分查询。
存在另一种方式吗?
USE [Northwind]
GO
ALTER PROCEDURE [dbo].[ProductosDiscontinuos]
-- Add the parameters for the stored procedure here
@discont bit,
@Unit INT,
@priceUnit INT,
@cName VARCHAR(30),
@CONSULTA nvarchar(MAX),
@tipoConsulta nvarchar(MAX)
AS
BEGIN
SET NOCOUNT ON;
SELECT
p.ProductName,
s.CompanyName,
p.QuantityPerUnit,
p.UnitPrice,
p.UnitsInStock,
p.UnitsOnOrder,
p.ReorderLevel,
p.Discontinued,
c.CategoryName,
c.Description
FROM
dbo.Categories c
INNER JOIN
dbo.Products p ON
c.CategoryID=p.CategoryID
INNER JOIN
Suppliers s ON
p.SupplierID=s.SupplierID
WHERE
@tipoConsulta =
(CASE
WHEN @CONSULTA='discontinued' THEN 'p.Discontinued=@discont'
WHEN @CONSULTA='UnitsOnOrder' THEN 'p.UnitsOnOrder > @Unit'
WHEN @CONSULTA='UnitPrice' THEN 'p.UnitPrice > @priceUnit'
WHEN @CONSULTA ='CompanyNAme' THEN 's.CompanyNAme Like %@cName%'
END)
END
执行脚本是......
USE [Northwind]
GO
DECLARE @return_value int
EXEC @return_value = [dbo].[ProductosDiscontinuos]
@discont = 1,
@Unit = NULL,
@priceUnit = NULL,
@cName = NULL,
@CONSULTA = N'discontinued',
@tipoConsulta = N'discontinued'
SELECT 'Return Value' = @return_value
但它没有给我任何显示!!
答案 0 :(得分:1)
一种方法是构建动态查询,或者只是简单地使用IF THEN ELSE。
ALTER PROCEDURE [dbo].[ProductosDiscontinuos]
@discont bit,
@Unit INT,
@priceUnit INT,
@cName VARCHAR(30),
@CONSULTA nvarchar(MAX),
@tipoConsulta nvarchar(MAX)
AS
BEGIN
SET NOCOUNT ON;
IF @CONSULTA = N'discontinued' THEN
BEGIN
SELECT
p.ProductName,
s.CompanyName,
p.QuantityPerUnit,
p.UnitPrice,
p.UnitsInStock,
p.UnitsOnOrder,
p.ReorderLevel,
p.Discontinued,
c.CategoryName,
c.Description
FROM dbo.Categories c
INNER JOIN dbo.Products p
ON c.CategoryID=p.CategoryID
INNER JOIN Suppliers s
ON p.SupplierID=s.SupplierID
WHERE
p.Discontinued=@discont
END
ELSE IF @CONSULTA = N'UnitsOnOrder' THEN
BEGIN
/* SELECT */
WHERE
p.UnitsOnOrder > @Unit
END
ELSE IF @CONSULTA = N'UnitPrice' THEN
BEGIN
/* SELECT */
WHERE
p.UnitPrice > @priceUnit
END
ELSE
BEGIN
/* SELECT */
WHERE
s.CompanyNAme Like %@cName% /* This is definetely non-SARGable; poor performance */
END
END
答案 1 :(得分:0)
...
WHERE
CASE
WHEN @CONSULTA = 'discontinued' AND p.Discontinued = @discont THEN 1
WHEN @CONSULTA = 'UnitsOnOrder' AND p.UnitsOnOrder > @Unit THEN 1
WHEN @CONSULTA = 'UnitPrice' AND p.UnitPrice > @priceUnit THEN 1
WHEN @CONSULTA = 'CompanyNAme' AND s.CompanyNAme LIKE '%' + @cName + '%' THEN 1
END = 1
这些类型的查询通常效率不高,但它应该满足您的要求。你的一些大写也是不一致的,我就像你拥有它一样。最后,我调整了LIKE
表达式,以正确连接百分比字符。