views:

150

answers:

3

I have a listbox select and I want when the user selects null for the empty string it produces to pull the nulls from the SQL table.

Here's what I have now. Blank strings return nothing because there are no empty fields in the table.

SELECT * FROM dbo.Table WHERE ID = " & TextBox2.Text & " and And Field1 IN (" & Msg1 & ")

How do I code that?

+1  A: 

Use an If statement. When your textbox is empty, have the SQL string contain "ID is null" instead of appending the textbox's value.

If (TextBox1.Text = "") Then
   ' use Is Null in your sql statement 
Else
   ' use the textbox text value in your sql statement
End If

(Assuming you're talking about the textbox and not whatever Msg1 is.)

Anthony Pegram
Where in the code does that belong?
Daniel
It belongs where you are constructing your SQL statement.
Anthony Pegram
Daniel
Yes, VBA supports code like this. Have you never written an If statement? It simply executes some code if some condition evaluates to true. Optionally, you can include an alternate piece of code if the condition evaluates to false (the `Else` clause).
Anthony Pegram
+1  A: 
 dim sql
 If (TextBox2.Text = null) Then
      sql = "SELECT * FROM dbo.Table WHERE ID is null and And Field1 IN (" & Msg1 & ")"
 Else
     sql = "SELECT * FROM dbo.Table WHERE ID = " & TextBox2.Text & " and And Field1 IN (" & Msg1 & ")"
 End If

See @John Saunders comment, you are risking sql injections. When passing paremeter to an sql query, be sure to use parameters, and not concatenating strings.

Am
Of course, we're assuming he knows about SQL Injection Attacks...
John Saunders
@John, *of course.*
Anthony Pegram
Not a problem. This is an internal application.
Daniel
@Am, for the record, that's not really valid VBA code. TextBox2.Text will not be null, and that's not a valid VBA `if` statement. `If .... Then ... Else ... End If`. Also, `==` is not used for equality in VB, it's just `=`.
Anthony Pegram
@anthony, tnx, used to writing c#...
Am
As am I! Although my background before was VB6/VBA.
Anthony Pegram
@Anthony: _you_ know it's "of course", and _I_ know it's "of course", but not all subsequent readers of this answer will know.
John Saunders
A: 
SELECT * FROM dbo.Table WHERE ID = " & TextBox2.Text & 
" And Field1 " & IIF(Trim(Msg1) = "", "IS NULL", "IN (" & Msg1 & ")")

Yes, it is crude.
One should not write query in this style.

EDIT: Corrected. Please check.

shahkalpesh
That looks cool, what is IIF and Trim?
Daniel
shahkalpesh
It's not working. Just bombs out. It says it's the (), but that can't be it.
Daniel
Please check. I have corrected the reply with ")" in it.
shahkalpesh