Powershell and SQL parameters. If empty string, pass DBNull

后端 未结 4 454

I got this parameter:

$objDbCmd.Parameters.Add(\"@telephone\", [System.Data.SqlDbType]::VarChar, 18) | Out-Null;
$objDbCmd.Parameters[\"@telephone\"].Value =         


        
4条回答
  •  北海茫月
    2021-01-18 08:07

    In PowerShell, you can treat null/empty strings as a boolean.

    $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:

    $Parameter.Value = $(if ($x) { $x } else { [DBNull]::Value })
    

    But I'd much rather wrap this up in a function like:

    function CatchNull([String]$x) {
       if ($x) { $x } else { [DBNull]::Value }
    }
    

提交回复
热议问题