0

有我的脚本:

$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:连接状态打开

4

1 回答 1

1

问题推测:您执行了一次发布的脚本片段,然后重新执行了这些行并将变量更改为$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,然后再关闭它。

于 2018-07-25T08:23:40.590 回答