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
}
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With