【发布时间】:2015-06-14 20:37:01
【问题描述】:
我正在使用 PowerShell,并且必须将数据从 .csv 文件导入到 SQL Server 数据库上已创建的表中。所以我不需要csv的标题行,只需写入数据即可。
这是我到目前为止所做的:
#Setup for SQL Server connection
#SQL Server Name
$SQLServer = "APPLIK02\SQLEXPRESS"
#Database Name
$SQLDBName = "code-test"
#Create the SQL Connection Object
$SQLConn = New-Object System.Data.SQLClient.SQLConnection
#Create the SQL Command Object, to work with the Database
$SQLCmd = New-Object System.Data.SQLClient.SQLCommand
#Set the connection string one the SQL Connection Object
$SQLConn.ConnectionString = "Server=$SQLServer;Database=$SQLDBName; Integrated Security=SSPI"
#Open the connection
$SQLConn.Open()
#Handle the query with SQLCommand Object
$SQLCmd.CommandText = $query
#Provide the open connection to the Command Object as a property
$SQLCmd.Connection = $SQLConn
#Execute
$SQLReturn=$SQLCmd.ExecuteReader()
Import-module sqlps
$tablename = "dbo."+$name
Import-CSV .\$csvFile | ForEach-Object Invoke-Sqlcmd
-Database $SQLDBName -ServerInstance $SQLServer
#-Query "insert into $tablename VALUES ('$_.Column1','$_.Column2')"
#Close
$SQLReturn.Close()
$SQLConn.Close()
【问题讨论】:
-
好吧,您已经注释掉了您的查询语句,这将导致问题。并且您删除了 ForEach-Object 上的括号。您还添加了很多随机代码并从网络上复制/粘贴,这些行中的任何一行都可能导致这些问题。我认为您采用的这种方法使这变得比需要的困难得多。请只尝试我已经给你的方法,并告诉我你遇到了什么错误。
-
你好 FoxDeploy,我昨天已经完成了,上面的代码只是在试验你的代码是如何工作的。谢谢
标签: sql-server powershell