Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading