简体   繁体   中英

Importing CSV columns into SQL table without Sqlcmd

I'm currently importing a csv file and inserting some of the results into a table.

Unfortunately I'm using Sqlcmd, but the module isn't installed on the relevant server and can't be installed (out of my control).

Is there a way to manage the exact same as the below, outside of 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:

# 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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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