合并两个存储过程以执行单独的SQL Server数据库搜索

时间:2015-07-16 14:52:50

标签: sql asp.net sql-server search stored-procedures

我正在使用存储过程搜索SQL Server数据库。我把它完美地显示在一个转发器中,用于搜索房子名称的文本框。在代码中,您可以看到它查找一个存储过程来执行搜索。任何人都可以帮助如何将两个存储过程合并为一个?它们都是单独工作但我需要让一个存储过程能够进行两种搜索。标有townland的下拉列表是独立的。

enter image description here

代码:

public void DisplaySearchResults(string strSearch)
{
    // Display search results in repeater
    SqlCommand cmd = new SqlCommand("spiSearchByString", new SqlConnection("Data Source=MAYDDD;Initial Catalog=HOB;Persist Security Info=True;User ID=ID; Password=password"));
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@SearchString", strSearch);

    cmd.Connection.Open();

    rptDataSearch.DataSource = cmd.ExecuteReader();
    rptDataSearch.DataBind();
}

搜索名称的存储过程:

CREATE PROCEDURE dbo.spiSearchByString
    @SearchString varchar(50)
AS 
    SELECT 
        Houses.Name, Houses.Id, Houses.Townland, 
        Houses.Near, Houses.Status, Houses.Built, Houses.Image  
    FROM 
        Houses
    WHERE 
        (Houses.Name LIKE '%' + @SearchString + '%' OR 
         Houses.Id LIKE '%' + @SearchString + '%')
    ORDER BY 
        Houses.Name 

    RETURN

搜索附近的存储过程:

CREATE PROCEDURE dbo.NearSearch
    @SearchString varchar(50)
AS 
    SELECT 
        Houses.Name, Houses.Id, Houses.Townland, Houses.Near, 
        Houses.Status, Houses.Built, Houses.Image  
    FROM 
        Houses
    WHERE 
        (Houses.Near LIKE '%' + @SearchString + '%' 
         OR Houses.Id LIKE '%' + @SearchString + '%')
    ORDER BY 
        Houses.Name 

    RETURN

2 个答案:

答案 0 :(得分:3)

您可以使用以下过程执行一个proc。它接收两个参数并基于哪一个为NULL。返回相关数据。它还允许同时指定两者,并允许NameNear过滤数据。

CREATE PROCEDURE dbo.CombinedSearch
(
    @HouseNearSearch VARCHAR(50) = NULL,
    @HouseNameSearch VARCHAR(50) = NULL
)
AS
    SELECT
        Houses.Name
        ,Houses.Id
        ,Houses.Townland
        ,Houses.Near
        ,Houses.Status
        ,Houses.Built
        ,Houses.IMAGE
    FROM Houses
    WHERE (@HouseNear IS NULL OR (Houses.Near LIKE '%' + @HouseNearSearch + '%' OR Houses.Id LIKE '%' + @HouseNearSearch + '%'))
 OR   (@HouseName IS NULL OR  (Houses.Name LIKE '%' + @HouseNameSearch + '%' OR Houses.Id LIKE '%' + @HouseNameSearch + '%'))
    ORDER BY Houses.Name
    RETURN

您的代码需要更新以确定将搜索字符串分配给哪个参数。

答案 1 :(得分:0)

过去,我一直致力于使用单个数据读取器返回多个记录集的解决方案。您可能必须制作并调用包含所有参数的包含存储过程,并依次调用这两个过程。然后,您可以按照此代码示例在单个调用中读取每个结果集; How To Handle Multiple Results by Using the DataReader in Visual C# .NET