提供搜索工具

时间:2011-03-23 10:30:27

标签: asp.net sql-server search

我有一个包含以下字段的网页

name,address,post

有三个文本框。我想向用户提供搜索工具。如果用户只输入名称并点击搜索它应该只按名称搜索,如果用户输入所有文本框的值,它应该用全部查询数据库3个值。如何明智地如何为所有搜索可能性编写sql查询?

2 个答案:

答案 0 :(得分:1)

select *
from Table1
where
  (coalesce(@Name, '') = '' or Name = @Name) and
  (coalesce(@Address, '') = '' or Address = @Address) and
  (coalesce(@Post, '') = '' or Post = @Post)  

答案 1 :(得分:1)

我更喜欢此选项用于查询。如果用户仅在其中一个字段中输入值,则将null传递给其他相应字段的参数。

Create PROCEDURE [dbo].[uspGetPeople]
@name varchar(50),
@Address varchar(200),
@Post varchar(5)
AS
SET NOCOUNT ON;
Select name, address, post 
from tblPeople 
where (name = @Name or @Name IS NULL) and
  (address = @Address or @Address IS NULL) and
  (post = @Post or @Post IS NULL)

调用存储过程的简单VB.NET示例:

Dim strName As String = NameTextBox.Value
Dim strAddress as string = AddressTextBox.Value
Dim strPost as string = PostTextBox.Value
Dim strSQL As String = "uspGetPeople"
Dim strConn As String = "My.Database.ConnectionString"
Dim cn As New SqlConnection(strConn)
Dim cmd As New SqlCommand(strSQL, cn)
cmd.CommandType = CommandType.StoredProcedure
If not string.isnullorempty(strName) then
    cmd.Parameters.AddWithValue("@Name", strName)
Else
    cmd.Parameters.AddWithValue("@Name", dbnull.value)
End if
If not string.isnullorempty(strPost) then
    cmd.Parameters.AddWithValue("@Post", strPost)
Else
    cmd.Parameters.AddWithValue("@Post", dbnull.value)
End if
If not string.isnullorempty(strAddress) then
    cmd.Parameters.AddWithValue("@Address", strAddress)
Else
    cmd.Parameters.AddWithValue("@Address", dbnull.value)
End if

Dim dr As SqlDataReader
Using cn
   cn.Open()
   dr = cmd.ExecuteReader
   While dr.Read
       'process records returned
       'dr("name")
       'dr("address")
       'dr("post")             
   End While
   cn.Close()
End Using