How to pass the parameter in SQL query from PowerShell

五迷三道 提交于 2019-12-13 02:15:39

问题


I have this code in PowerShell, that executes SQL query to UPDATE my table:

$Connection=new-object data.sqlclient.sqlconnection "server=server;database=mydb;trusted_connection=true;"
$Connection.open()

For ( $i = 0; $i -le $ActID.Length; $i ++ ) { 
    $cmd = New-Object System.Data.SqlClient.SqlCommand
    $cmd.Connection = $Connection
    $cmd.CommandText = 
    "
    update Table 
    set Note = @PATH
    "
    $cmd.Parameters.Add("@PATH", $ActID[$i].Values) | Out-Null

    $cmd.ExecuteNonQuery()
}

I tried to update the table with the variable defined in this string:

$cmd.Parameters.Add("@PATH", $ActID[$i].Values) | Out-Null

But when I execute the script the error log says that there is no value passed in $ActID[$i]

Are there other methods to pass parameters (variables) in powershell queries?


回答1:


What could be the mistake:

$i -le $ActID.Length;

it should be probably

$i -lt $ActID.Length;

You could also use piping which simplifies the code:

$actId | % { ..... $cmd.Parameters.Add("@PATH", $_.Values) | Out-Null .... }

Besides that the property you use is Values - is it really what you wanted? Values looks like a collection of something. Maybe you wanted to use a single value.



来源:https://stackoverflow.com/questions/2266758/how-to-pass-the-parameter-in-sql-query-from-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!