Powershell和SQL参数。如果为空字符串,则传递DBNull [英] Powershell and SQL parameters. If empty string, pass DBNull

查看:88
本文介绍了Powershell和SQL参数。如果为空字符串,则传递DBNull的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下参数:

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

字符串 $ objUser.Telephone 所在的位置是空的。如果为空,如何将其转换为 [DBNull] :: Value

Where the string $objUser.Telephone can be empty. If it's empty, how can I convert it to [DBNull]::Value?

我尝试过:

if ([string]:IsNullOrEmpty($objUser.Telephone)) { $objUser.Telephone = [DBNull]::Value };

但这给了我错误:


使用 0参数调用 ExecuteNonQuery的异常:无法将参数值从ResultPropertyValueCollection转换为字符串。

Exception calling "ExecuteNonQuery" with "0" argument(s): "Failed to convert parameter value from a ResultPropertyValueCollection to a String."

如果我将其转换为字符串,它将插入一个空字符串 ,而不是 DBNull

And if I convert it to a string, it inserts an empty string "", and not DBNull.

如何实现?

谢谢。

推荐答案

在PowerShell中,您可以将空/空字符串视为布尔值。

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 }
}

这篇关于Powershell和SQL参数。如果为空字符串,则传递DBNull的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆