2011-03-23 158 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