SQL查询Powershell中的变量

时间:2018-07-25 07:56:58

标签: sql powershell mcafee

有我的剧本:

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

1 个答案:

答案 0 :(得分: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,然后将其关闭。