Hi All,
Sharing a Powershell method to import CSV to sql table, I am attaching the example CSV as well.
First step is to create the Header in SQL table same as in CSV that needs to be Imported.
I am sharing the example that I have followed for demonstration of this script:
Download the Script : https://gallery.technet.microsoft.com/scriptcenter/Import-to-SQL-Table-from-7ffe3a5d
- Created the Test Database by logging in to SQL management studio
- After I have created the Database with Name TESTDB, we need to run the query to create a Table with the same headers as CSV that needs to be imported.
- Below query needs to be run (In have included that in zip)
- Now the Table with Header is created
After sql part is completed you just need to execute the .ps1 script in the zip file.
you just need to edit the .ps1 file according to your requirement.
for example:-
$sql_instance_name = ‘ServerSQL01\LAB’
$db_name = ‘testdb’
Here is the result of import:
Pre-requisties:- SQL Powershell module
#################################################################### # Author: Vikas Sukhija # Date: 07/17/2015 # Reviewer: # Desc : Import CSV file to SQL table # ##################################################################### ########################Load SQL Snapin############################## If ((Get-PSSnapin | where {$_.Name -match "SqlServerCmdletSnapin100"}) -eq $null) { Add-PSSnapin SqlServerCmdletSnapin100 } If ((Get-PSSnapin | where {$_.Name -match "SqlServerProviderSnapin100"}) -eq $null) { Add-PSSnapin SqlServerProviderSnapin100 } $sql_instance_name = 'ServerSQL01\LAB' $db_name = 'testdb' $impcsv = ".\Example.csv" $data = import-csv $impcsv $count = 1 foreach($i in $data){ $country = $i.country $name = $i.name $SAMAccountName = $i.SAMAccountName $FirstName = $i.FirstName $Lastname = $i.Lastname $UserSamname = $i.UserSamname $Access = $i.Access $query = "INSERT INTO testlist (country,name, SAMAccountName, FirstName, Lastname, UserSamname, Access) VALUES ('$country','$name','$SAMAccountName','$FirstName','$Lastname','$UserSamname','$Access')" $impcsv = invoke-sqlcmd -Database $db_name -Query $query -serverinstance $sql_instance_name write-host "Processing row ..........$count" -foregroundcolor green $count = $count + 1 } ###################################################################
Tech Wizard