How to create null SQL parameter for a UniqueIdentifier?

While doing

If Me.Id_Padre Is Nothing Then
    comandoSQL.Parameters.Add("@Id_Padre", SqlDbType.UniqueIdentifier).Value = DBNull.Value
Else
    comandoSQL.Parameters.Add("@Id_Padre", SqlDbType.UniqueIdentifier).Value = New Guid(Me.Id_Padre)
End If

gives me no error, this instead

comandoSQL.Parameters.Add("@Id_Padre", SqlDbType.UniqueIdentifier).Value = IIf(Me.Id_Padre Is Nothing, DbNull.Value, New Guid(Me.Id_Padre))

gives me an error saying the value cannot be null.

Any idea?

Thank you in advance

>Solution :

What is happening is that Iif will always evaluate (run) both parts. So the last part will throw an exception since Id_Padre is nothing. From documentation (https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/iif-function):

IIf always evaluates both truepart and falsepart, even though it
returns only one of them. Because of this, you should watch for
undesirable side effects. For example, if evaluating falsepart results
in a division by zero error, an error occurs even if expr is True.

I recommend using If instead to avoid this (https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/if-operator) so:

comandoSQL.Parameters.Add("@Id_Padre", SqlDbType.UniqueIdentifier).Value = If(Me.Id_Padre Is Nothing, DbNull.Value, New Guid(Me.Id_Padre))

Leave a Reply