Using PowerShell inserts string values ​​into SQL Server DB.

I have a long list of values ​​to insert into a single column SQL table of columns. I am using the following code. However, this takes a lot of 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               
        }
+4
source share
2 answers

Try this, it will ride on one connection, so you will avoid costly overheads according to @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()
+10
source

, Sql . , , bcp TSQL. Sql Server .

, ,

-- Sample tables
create table myTable(data varchar(32))
create table staging(data varchar(32))
-- Some demo values
insert myTable values ('a')
insert myTable values ('b')
insert myTable values ('c')
insert myTable values ('d')

-- More demo values, note there is a duplicate
-- You'd fill this table with bcp. For illustration purposes,
-- data is inserted instead of bulk copying.
insert staging values ('e')
insert staging values ('c')
insert staging values ('f')

-- Let look the table first
select data from mytable

-- Create a CTE that contains values from staging that are not in myTable
;with mt (sdata) as(
select data from staging s where data not in (select data from mytable)
)
-- Insert new values
insert into mytable(data) select sdata from mt

-- Let look the final result
select data from mytable
0

Source: https://habr.com/ru/post/1535835/


All Articles