简体   繁体   中英

T SQL - Build Select Statement

Im using Sql Server. In a stored procedure I need to build a sql select based on the parameters passed. based on the parameter i need to add conditions to the WHERE clause. I need this sql to declare a cursor.

What I need is something like

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>

What would be the best way to do this in t-sql ?

If you just want to filter by certain conditions depending on whether certain parameters are set or not, simply include the parameters in your WHERE-clause like so:

SELECT username FROM mytable 
WHERE <StaticCondition>
    AND (@Parameter1 IS NULL OR <Parameter1Condition>)
    AND (@Parameter2 IS NULL OR <Parameter2Condition>)
    AND ...

This approach can be used no matter if the output should be used directly, or if you need the select statement to declare a cursor.

I know it's generally frowned upon just to post a link, but this is probably the best article I've found on 'search SQL' options & is pretty detailed.

http://www.sommarskog.se/dyn-search-2008.html

overall query, eg

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)**

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM