sql - Powershell 和 SQL 参数。如果为空字符串,则传递 DBNull

标签 sql powershell dbnull

我得到了这个参数:

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

其中字符串$objUser.Telephone可以为空。如果它是空的,我如何将其转换为 [DBNull]::Value ?

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

但这给了我错误:

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



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

如何做到这一点?

谢谢。

最佳答案

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

$x = $null
if ($x) { 'this wont print' }

$x = ""
if ($x) { 'this wont print' }

$x = "blah"
if ($x) { 'this will' }

所以......话虽如此,你可以这样做:
$Parameter.Value = $(if ($x) { $x } else { [DBNull]::Value })

但我更愿意将其封装在一个函数中,例如:
function CatchNull([String]$x) {
   if ($x) { $x } else { [DBNull]::Value }
}

关于sql - Powershell 和 SQL 参数。如果为空字符串,则传递 DBNull,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/920991/

相关文章:

.net - 检查 DBNull 然后分配给变量的最有效方法?

mysql - SQL 按不同字段排序

php - 如何实现字符串值到日期格式

Powershell 陷阱 [异常] 没有捕捉到我的错误

powershell - 在 powershell 脚本中尝试/捕获 aws cli 错误

c# - 如何处理System.DBNull?

sql-server-2005 - 为什么我不能将 DBNull.Value 插入到 sql server 2005 中的可为 null 的图像字段中?

sql - 如何获取有关给定包中声明的所有类型数据的信息

sql - 需要帮助将表从 sql server 2008 导出到文本文件

Node.js + Powershell : how to encode Unicode characters when using stdin. 写入