SQL 在 powershell 中查询变量

SQL query to variable in powershell

这是我的脚本:

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=xxxxx;Database=xxxx;User ID=xxxx\xxxx;Password=xxxxx;Trusted_Connection=True;"
$SqlConnection.Open()
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "SELECT version FROM xxxx.dbo.EPOAvertContentUpdates where productId=VSCANDAT1000"
$SqlCmd.Connection = $SqlConnection
$dbname = $SqlCmd.ExecuteScalar()
$SqlConnection.Close()
Write-output "version" $dbname

我得到的错误:

Exception calling "ExecuteScalar" with "0" argument(s): "ExecuteScalar requires an open and available Connection. The connection's current state is closed."
At line:12 char:1
+ $results = $SqlCmd.ExecuteScalar()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : InvalidOperationException

我想从我们的数据库中获取产品 ID 号,并将其存储到变量中以便与其他变量进行比较。任何建议是什么问题? 感谢您的帮助!

@vonPryz: 连接状态打开

问题推测: 您执行了一次发布的脚本片段,然后重新执行这些行并将变量更改为 $results:

$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "SELECT version FROM xxxx.dbo.EPOAvertContentUpdates where productId=VSCANDAT1000"
$SqlCmd.Connection = $SqlConnection

但是这次换另一个数据库?

执行任何其他TSQL时,请确保先打开SQL连接,执行TSQL,然后关闭它。