Search code examples
c#vb.netsqlclient

Conditional AddWithValue as one-liner


I'm looking for a simple one-liner to accomplish the following in the SqlClient namespace, to save typing out all the if-else statements. Assuming:

Dim cmd As New SqlCommand("MyStoredProcName", MySqlConnection) 

This is what I'm trying to one-line:

If MyDataSet.Tables("MyTableName").Columns.Contains("MyColumnName") Then
    cmd.Parameters.AddWithValue("@SQLParameter", True)
Else
    cmd.Parameters.AddWithValue("@SQLParameter", False)
End If

Anyone have anything clever and readable? C# fine too.

EDIT: n8wrl's answer does what I asked for, but I should have been more clear: I am looking for the more generic ability to add any data type to the SQLparameter. i.e. Instead of "True or "False" it could be StringA and StringB.

If MyDataSet.Tables("MyTableName").Columns.Contains("MyColumnName") Then
    cmd.Parameters.AddWithValue("@SQLParameter", "StringA")
Else
    cmd.Parameters.AddWithValue("@SQLParameter", "StringB")
End If

Solution

  • This should work:

    cmd.Parameters.AddWithValue("@SQLParameter", MyDataSet.Tables("MyTableName").Columns.Contains("MyColumnName"))
    

    You might want to consider the fact that the original version might be more readable.

    UPDATE:

    If you need to have values that are not boolean, you can use the IIf function like this:

    cmd.Parameters.AddWithValue("@SQLParameter", IIf(MyDataSet.Tables("MyTableName").Columns.Contains("MyColumnName"), "StringA", "StringB"))