使用PowerShell将字符串值插入SQL Server数据库。

4

我有一个长列表的值需要插入到单列SQL服务器表中。我使用以下代码。但是,它需要很长时间。是否有更简单的方法来实现这个目标?

$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               
        }
2个回答

10

试试这个,它会在单个连接上运行,因此您将避免像@vonPryz所说的昂贵开销:

尝试此方法,它将使用单个连接,从而避免像 @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()

在我把打开和关闭放在foreach块内之前,我一直遇到错误。 - Flat Cat
如果您在每次插入时打开/关闭连接,将会削弱单个连接的优势(速度)。请提出一个新问题,我相信会有人能够帮助您解决错误。 - Raf

0

如果你为每个查询打开一个新的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's 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's look the final result
select data from mytable

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接