These are the two easy ways to import data from a CSV file into a table of a SQL Server Database – Using Bulk Insert and Using SQL Server Management Studio.
Consider the following data
1,test,89300
2,testing,52801
3,test,1000
2,testing,52801
3,test,1000
Create a file name test.csv in your system and add the data shown above in that file
Create a test table
CREATE TABLE test(
id int,
names varchar(100),
amount decimal(12,2)
)
id int,
names varchar(100),
amount decimal(12,2)
)
Method 1: Using Bulk Insert
Here’s the same query for you to try out
bulk insert test from 'F:\test.csv'
with
(
fieldterminator=',',
rowterminator='\n'
)
with
(
fieldterminator=',',
rowterminator='\n'
)
The above code reads data from the file located at F:\text.csv and splits data into different
columns based on the fieldterminator ‘,’ (comma) and into different rows based on therowterminator '\n' (\n is for newline).
columns based on the fieldterminator ‘,’ (comma) and into different rows based on therowterminator '\n' (\n is for newline).
Now if you do a SELECT * FROM test you will get the following output
Method 2: Using SQL Server Management Studio
Right click on your database > Tasks > Import data
Select the datasource as Flat file. Select the file using the browse button or type the file path and name directly and click Next
Select row terminator as {CR}{LF} and column terminator as comma{,} and click Next
Select Destination as your server and select the database where the table exists. Click Next
The wizard will import the data and show you the details about the data which was imported
No comments:
Post a Comment