所以我需要每次腳本運行時用文本文件中的數據更新現有的表。我當前的代碼會丟棄表格並在每次運行時創建一個新表格,這會導致我需要避免大約10秒的延遲。我想改爲更新數據而不重新創建表(希望緩解延遲?)。我知道UPDATE
或MERGE
命令可以用於此,但一直未能弄清楚語法。使用Powershell更新/插入SQL表
Function CreateAnalystTable($location, $file, $extension, $server, $database)
{
$full = $location + $file + $extension
$all = Get-Content $full
$columns = $all[0]
$columns = $columns.Replace(";","] VARCHAR(255), [")
$table = "CREATE TABLE " + $file + "([" + $columns + "] VARCHAR(255))"
$connection = New-Object System.Data.SqlClient.SqlConnection
$buildTable = New-Object System.Data.SqlClient.SqlCommand
$insertData = New-Object System.Data.SqlClient.SqlCommand
$connection.ConnectionString = "Data Source=" + $server + ";Database=" + $database + ";integrated security=true"
$buildTable.CommandText = $table
$buildTable.Connection = $connection
## Added to function
$x = 0
$insertData.CommandText = "EXECUTE stp_CommaBulkInsert @1,@2"
$insertData.Parameters.Add("@1", $full)
$insertData.Parameters.Add("@2", $file)
$insertData.Connection = $connection
$connection.Open()
$buildTable.ExecuteNonQuery()
$connection.Close()
## Added to function
$x = 1
if ($x = 1)
{
$connection.Open()
$insertData.ExecuteNonQuery()
$connection.Close()
}
}
CreateAnalystTable -location "PATH" -file "FILE" -extension ".txt" -server "SERVER" -database "DB"
SQL:
CREATE PROCEDURE stp_CommaBulkInsert
@file NVARCHAR(250), @table NVARCHAR(250)
AS
BEGIN
DECLARE @f NVARCHAR(250), @t NVARCHAR(250), @s NVARCHAR(MAX)
SET @f = @file
SET @t = @table
SET @s = N'BULK INSERT ' + @t + '
FROM ''' + @f + '''
WITH (
FIELDTERMINATOR = '';''
,ROWTERMINATOR = ''0x0a''
,FIRSTROW=2
)'
EXEC sp_executesql @s
END
任何幫助表示讚賞
[This](http://stackoverflow.com/questions/16979860/sql-update-table-from-a-text-file)可能會幫助你。 – BJones