通过一次连接将数组中的PowerShell值插入SQL Server表中

时间:2018-07-03 14:47:12

标签: sql-server powershell

如果我想在一个连接中将值插入数组,如何修改下面的代码?到目前为止,除非我将$ Connection.Open()和$ Connection.Close()放入for循环中,否则我将得到错误“已经有一个与该命令相关联的打开的DataReader,必须先关闭它”,这将使我花很多钱。单个连接的速度。

$list = 'aaa','bbb','cccc','ddddd','eeeee','ffff'
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "server='$Server';database='$Database';trusted_connection=true;"
$Connection.Open()
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
foreach($i in $list) {
    $sql ="if not exists (select 1 from [bfs] where [key] = '$i' ) 
        begin 
            insert bfs
            select '$i'
        end
    " 
$Command.CommandText = $sql
$Command.ExecuteReader()
}
$Connection.Close()

1 个答案:

答案 0 :(得分:1)

尝试使用ExecuteNonQuery()而不是ExecuteReader()。 ExecuteNonQuery()不会构建DataReader。

...
$Command.CommandText = $sql
$Command.ExecuteNonQuery()
...