在 SQL Server DB 中使用 PowerShell 插入字符串值. [英] Using PowerShell insert string values in SQL Server DB.
本文介绍了在 SQL Server DB 中使用 PowerShell 插入字符串值.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一长串需要插入到单列 SQL 服务器表中的值.我使用以下代码.然而,这需要很长时间.有没有更简单的方法来实现这一目标?
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
}
推荐答案
试试这个,它会在一个连接上运行,这样你就可以避免@vonPryz 的昂贵开销:
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()
这篇关于在 SQL Server DB 中使用 PowerShell 插入字符串值.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文