我正在使用Sql Server。在存储过程中,我需要根据传递的参数构建一个sql select。 基于我需要为WHERE子句添加条件的参数。 我需要这个sql来声明一个游标。
我需要的是像
DECLARE mycursor CURSOR LOCAL FOR
SELECT username FROM mytable Where <condition1>
IF(parameter 1 is not empty)
AND <conditions>
IF(parameter 2 is not empty)
AND <condition3>
在t-sql中执行此操作的最佳方法是什么?
答案 0 :(得分:1)
如果您只想根据某些参数是否设置过滤某些条件,只需在WHERE子句中包含参数,如下所示:
SELECT username FROM mytable
WHERE <StaticCondition>
AND (@Parameter1 IS NULL OR <Parameter1Condition>)
AND (@Parameter2 IS NULL OR <Parameter2Condition>)
AND ...
无论是直接使用输出,还是需要select语句来声明游标,都可以使用此方法。
答案 1 :(得分:0)
我知道发布一个链接通常不赞成,但这可能是我在搜索SQL&#39;上发现的最好的文章。选项&amp;非常详细。
http://www.sommarskog.se/dyn-search-2008.html
整体查询,例如
http://www.sommarskog.se/dynsearch-2008/search_orders_4a.sp
** SELECT o.OrderID, o.OrderDate, od.UnitPrice, od.Quantity,
c.CustomerID, c.CompanyName, c.Address, c.City, c.Region,
c.PostalCode, c.Country, c.Phone, p.ProductID,
p.ProductName, p.UnitsInStock, p.UnitsOnOrder
FROM Orders o
JOIN [Order Details] od ON o.OrderID = od.OrderID
JOIN Customers c ON o.CustomerID = c.CustomerID
JOIN Products p ON p.ProductID = od.ProductID
WHERE (o.OrderDate >= @fromdate OR @fromdate IS NULL)
AND (o.OrderDate <= @todate OR @todate IS NULL)
AND (od.UnitPrice >= @minprice OR @minprice IS NULL)
AND (od.UnitPrice <= @maxprice OR @maxprice IS NULL)
AND (o.CustomerID = @custid OR @custid IS NULL)
AND (c.CompanyName LIKE @custname + '%' OR @custname IS NULL)
AND (c.City = @city OR @city IS NULL)
AND (c.Region = @region OR @region IS NULL)
AND (c.Country = @country OR @country IS NULL)
AND (od.ProductID = @prodid OR @prodid IS NULL)
AND (p.ProductName LIKE @prodname + '%' OR @prodname IS NULL)**