我有一长串值需要插入到单列 SQL Server 表中。我使用以下代码。然而,这需要很长时间。有没有更简单的方法来实现这一目标?
$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 那样产生昂贵的开销:
$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 - 使用 PowerShell 在 SQL Server DB 中插入字符串值。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22974931/