Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PowerShell insert string values in SQL Server DB.

I have a long list of values that need to be inserted in a single column SQL server table. I use the following code. However, it takes a long time. Is there an easier way to achieve this?

$list = 'aaa','bbb','cccc','ddddd','eeeee','ffff'....

    foreach($i in $list) {
        $sql ="if not exists (select 1 from [table_nm] where column_nm = '$i' ) 
            begin 
              insert table_nm
              select '$i'
            end
            " 

        Invoke-Sqlcmd -ServerInstance $server -Database db_nm -query $sql               
        }
like image 317
RaviLobo Avatar asked Dec 25 '22 10:12

RaviLobo


1 Answers

Try this, it will ride on a single connection so you will avoid the expensive overhead as per @vonPryz:

$list = 'aaa','bbb','cccc','ddddd','eeeee','ffff'....
$server = "server1"
$Database = "DB1"

$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 [table_nm] where column_nm = '$i' ) 
        begin 
        insert table_nm
        select '$i'
        end
    " 
    $Command.CommandText = $sql
    $Command.ExecuteReader()
}
$Connection.Close()
like image 148
Raf Avatar answered Dec 28 '22 07:12

Raf