如何根据vb.net中六个文本框的用户输入制作一个dinamic sql请求?

时间:2017-04-12 08:40:56

标签: vb.net

我正在为我的应用程序创建一个搜索精简程序,我正在进行查询,根据用户填写的表单返回相关列表。问题是表单字段是可选的,我无法计算如何根据输入的字段进行查找更改。

1 个答案:

答案 0 :(得分:-1)

我们在SQL中所做的是执行以下操作:

Select * from table where 
    (ISNULL(@field1, '') = '' OR @field1 = table.field1) 
    and (ISNULL(@field2, '') = '' OR @field2 = table.field2)  
    and (ISNULL(@field3, '') = '' OR @field3 = table.field3)  
    and (ISNULL(@field4, '') = '' OR @field4 = table.field4)  
    and (ISNULL(@field5, '') = '' OR @field5 = table.field5)  
    and (ISNULL(@field6, '') = '' OR @field6 = table.field6)

或在VB中

dim sql as string = "Select * from table where 
    (ISNULL(" & textBobx1.text & ", '') = '' OR " & textBobx1.text & "= table.field1) 
    and (ISNULL(" & textBobx2.text & ", '') = '' OR " & textBobx2.text & "= table.field2)  
    and (ISNULL(" & textBobx3.text & ", '') = '' OR " & textBobx3.text & "= table.field3)  
    and (ISNULL(" & textBobx4.text & ", '') = '' OR " & textBobx4.text & "= table.field4)  
    and (ISNULL(" & textBobx5.text & ", '') = '' OR " & textBobx5.text & "= table.field5)  
    and (ISNULL(" & textBobx6.text & ", '') = '' OR " & textBobx6.text & "= table.field6)"

您只需要传递所有字段,确保如果表单上的字段未填写通过空白或者可以调用您在文本框文本中传递的函数,则返回NULL。