Click here to Skip to main content
15,893,814 members
Please Sign up or sign in to vote.
1.30/5 (3 votes)
See more:
How to read text file data in sql server 2008???

I have a one text file and data insert into database.
Posted
Updated 11-Nov-19 23:27pm
v2
Comments
Richard MacCutchan 11-Oct-13 3:19am    
With notepad.

Hello,

You can use BULK INSERT[^] for this.

e.g.
SQL
BULK INSERT csv_test
FROM 'F:\csv_data.txt'
WITH
(
    FIELDTERMINATOR = ',',
    ROWTERMINATOR = '\n'
)
GO

The above examples inserts data from a CSV text file into SQL server table.

Regards,
 
Share this answer
 
Assuming that you mean to read the file in C# and insert it into your SQL Db (otherwise why mention C# in the tags?) then exactly how you do it depends on what kind of column you have created in SQL.
If it is VARCHAR:
C#
string myFileString = File.ReadAllText(path);
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand com = new SqlCommand("INSERT INTO myTable (myColumn) VALUES (@TEXT)", con))
        {
        com.Parameters.AddWithValue("@TEXT", myFileString);
        com.ExecuteNonQuery();
        }
    }
If it is VARBINARY:
C#
byte[] myFiledata = File.ReadAllBytes(path);
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand com = new SqlCommand("INSERT INTO myTable (myColumn) VALUES (@DATA)", con))
        {
        com.Parameters.AddWithValue("@DATA", myFileData);
        com.ExecuteNonQuery();
        }
    }
 
Share this answer
 
Comments
Prasad Khandekar 11-Oct-13 5:26am    
My 5+, I totally missed C# tag.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900