简体   繁体   English

在没有 Sqlcmd 的情况下将 CSV 列导入 SQL 表

[英]Importing CSV columns into SQL table without Sqlcmd

I'm currently importing a csv file and inserting some of the results into a table.我目前正在导入一个 csv 文件并将一些结果插入到一个表中。

Unfortunately I'm using Sqlcmd, but the module isn't installed on the relevant server and can't be installed (out of my control).不幸的是,我使用的是 Sqlcmd,但该模块未安装在相关服务器上,无法安装(我无法控制)。

Is there a way to manage the exact same as the below, outside of SqlCMD?有没有办法在 SqlCMD 之外管理与下面完全相同的方法?

Example Code:示例代码:


$server = 's'
$database = 'd'
$table = 't'

Import-CSV C:\Test\Test.csv | ForEach-Object {Invoke-Sqlcmd `
  -Database $database -ServerInstance $server `
  -Query "INSERT INTO $table VALUES ('$($_."Column One")',
                                     '$($_."Column Two")',
                                      NULL,
                                     '$($_.""Column Three"")')"
    }


You can try the ADO.Net objects:您可以尝试 ADO.Net 对象:

# Hardcode the table name, unless you *REALLY* trust your users.
$SQL = "INSERT INTO TableName VALUES (@Column1, @Column2, NULL, @Column3)"

$conn = new-Object System.Data.SqlClient.SqlConnection
$conn.ConnectionString = "Server=$server;Database=$database;Integrated Security=True;"
$cmd = new-Object System.Data.SqlClient.SqlCommand($SQL, $conn)

# Use actual types and lengths from the database here
$c1 = $cmd.Parameters.Add("@Column1", [System.Data.SqlDbType]::NVarChar, 20)
$c2 = $cmd.Parameters.Add("@Column2", [System.Data.SqlDbType]::NVarChar, 20)
$c3 = $cmd.Parameters.Add("@Column3", [System.Data.SqlDbType]::NVarChar, 20)

$conn.Open()

Import-CSV C:\Test\Test.csv | ForEach-Object {
   $c1.Value = $_."Column One"
   $c2.Value = $_."Column Two"       
   $c3.Value = $_."Column Three"

   $cmd.ExecuteNonQuery()
}
$conn.Close()

This will also fix any issues with apostrophes in the data, which would have caused HUGE problems in the original.这也将解决数据中撇号的任何问题,这会在原始数据中造成巨大的问题。

You could try and use the bulk insert command, search for a simple SQL connection and query execution - the exact one that Joel Coehoorn posted, if you have bulk permissions and the server has access to the file itself.您可以尝试使用批量插入命令,搜索简单的 SQL 连接并执行查询 - 如果您拥有批量权限并且服务器有权访问文件本身,那么正是 Joel Coehoorn 发布的那个。 you could also add parameters to it and then call it however you see fit.您也可以向它添加参数,然后以您认为合适的方式调用它。 Meaning you could foreach files in folder, call the bulk insert with your connection.这意味着您可以 foreach 文件夹中的文件,使用您的连接调用批量插入。

BULK INSERT TableName
FROM 'LinkToSourceFile.csv' WITH (
FIELDTERMINATOR = '\t',
ROWTERMINATOR = '\n',
FIRSTROW = 2
    );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM