Question:
I got this parameter:
1 2 3 |
$objDbCmd.Parameters.Add("@telephone", [System.Data.SqlDbType]::VarChar, 18) | Out-Null; $objDbCmd.Parameters["@telephone"].Value = $objUser.Telephone; |
Where the string $objUser.Telephone
can be empty. If it’s empty, how can I convert it to [DBNull]::Value
?
I tried:
1 2 |
if ([string]:IsNullOrEmpty($objUser.Telephone)) { $objUser.Telephone = [DBNull]::Value }; |
But that gives me the error:
Exception calling “ExecuteNonQuery” with “0” argument(s): “Failed to convert parameter value from a ResultPropertyValueCollection to a String.”
And if I convert it to a string, it inserts an empty string ""
, and not DBNull
.
How can this be accomplished?
Thanks.
Answer:
In PowerShell, you can treat null/empty strings as a boolean.
1 2 3 4 5 6 7 8 9 |
$x = $null if ($x) { 'this wont print' } $x = "" if ($x) { 'this wont print' } $x = "blah" if ($x) { 'this will' } |
So…. having said that you can do:
1 2 |
$Parameter.Value = $(if ($x) { $x } else { [DBNull]::Value }) |
But I’d much rather wrap this up in a function like:
1 2 3 4 |
function CatchNull([String]$x) { if ($x) { $x } else { [DBNull]::Value } } |