使用或者使用sql语句进行搜索

时间:2014-02-28 13:35:38

标签: sql-server

我想通过卖家的名称,价格或用户名搜索产品,如果其中一个未被选中,例如,如果只插入名称,则该语句会查找具有此名称的所有项目,如果我预先准备了更多信息,例如价格,项目在已插入名称的项目中查找并查找具有当前价格的项目

我已经到了这一点但是我仍然无法做更多你能帮忙吗

Declare @endate datetime ,
        @name varchar(50),
        @cat varchar(50),
        @to varchar (50),
        @from varchar(50),
        @user varchar(100),
        @con varchar(100)

        AS
SELECT  *
FROM
(
    SELECT  Top(6)
            Item.ItemID,
            Auction.AuctionID,
            Item.Name,
            Item.Description,
            Item.Quantity,
            Item.Condition,
            Category.CategoryName AS Expr1,
            Auction.EndDate,
            Auction.CurrencyValuePost,
            Image.Image,
            ROW_NUMBER() OVER (PARTITION BY Item.ItemID ORDER BY Item.ItemID ASC) AS RN
    FROM Item
    INNER JOIN Category ON Item.CategoryID = Category.CategoryID
    INNER JOIN Auction ON Item.ItemID = Auction.ItemID
    INNER JOIN Seller ON Item.SellerID = Seller.SellerID
    INNER JOIN Member ON Seller.MemberID = Member.MemberID
    LEFT OUTER JOIN Image ON Item.ItemID = Image.ItemID
    WHERE   Auction.Status = 'BID'
    And Auction.EndDate > @endate
    And Category.CategoryName = @cat
    And Item.Name = @name
    And CurrencyValuePost BETWEEN @from and @to
    And Item.Condition = @con
    And Member.Username = @user
) AS T
WHERE RN = 1

2 个答案:

答案 0 :(得分:3)

在WHERE子句中,您可以执行以下操作:

WHERE 
     (@name IS NULL OR Item.Name = @name)
AND 
     (@cat  IS NULL OR Category.CategoryName = @cat)
AND
     (@user IS NULL OR Member.Username = @user)
AND 
     (...any additional clauses)    

答案 1 :(得分:0)

这是您的查询的样子:

Declare @endate datetime ,
        @name varchar(50),
        @cat varchar(50),
        @to varchar (50),
        @from varchar(50),
        @user varchar(100),
        @con varchar(100);


SELECT  *
FROM
(
    SELECT  Top(6)
            Item.ItemID,
            Auction.AuctionID,
            Item.Name,
            Item.Description,
            Item.Quantity,
            Item.Condition,
            Category.CategoryName AS Expr1,
            Auction.EndDate,
            Auction.CurrencyValuePost,
            Image.Image,
            ROW_NUMBER() OVER (PARTITION BY Item.ItemID ORDER BY Item.ItemID ASC) AS RN
    FROM Item
    INNER JOIN Category ON Item.CategoryID = Category.CategoryID
    INNER JOIN Auction ON Item.ItemID = Auction.ItemID
    INNER JOIN Seller ON Item.SellerID = Seller.SellerID
    INNER JOIN Member ON Seller.MemberID = Member.MemberID
    LEFT OUTER JOIN Image ON Item.ItemID = Image.ItemID
    WHERE   Auction.Status = 'BID'
    And Auction.EndDate > @endate
    And (@cat = '' or Category.CategoryName = @cat)
    And (@name = '' or Item.Name = @name)
    And (@con = '' or Item.Condition = @con)
    And CurrencyValuePost BETWEEN @from and @to
    And Member.Username = @user

) AS T
WHERE RN = 1;