2011-03-23 84 views
0

我有一个网页有以下字段提供搜索工具

name,address,post 

三个textboxes.I要提供搜索工具的用户user.if只需输入姓名和点击搜索应该只能由搜索名称,如果用户输入所有文本框的值,它应该用全部3个值来查询数据库。就像明智的我该如何为所有搜索可能性编写sql查询?

回答

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

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

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