Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stored Procedure to Open and Read a text file

I am looking for a stored procedure code that will open a text file, read in several thousand lines, and add the code to a table in the database. Is there a simple way to implement this in T-SQL?

like image 355
Cyber Slueth Omega Avatar asked Dec 13 '10 00:12

Cyber Slueth Omega


People also ask

How do I open a text file in SQL?

Syntax: SELECT * FROM OPENROWSET (BULK 'file_path', SINGLE_CLOB) as correlation_name; This query will read the content of the text file and return it as a single column in a table named Bulkcolumn. The correlation name is mandatory to specify.

How do I view stored procedure text?

Using SQL Server Management StudioExpand Stored Procedures, right-click the procedure and then select Script Stored Procedure as, and then select one of the following: Create To, Alter To, or Drop and Create To. Select New Query Editor Window. This will display the procedure definition.

How read data from text file and save to database in SQL Server?

Go to database Oct_7_database and right click on the database. After that select Tasks, then select import data by pressing enter key. Step 5: Welcome to Wizard. Step 6: Choose a Data Source.

How do I load a text file into a SQL Server table?

Open SQL Server Management Studio. Connect to an instance of the SQL Server Database Engine or localhost. Expand Databases, right-click a database (test in the example below), point to Tasks, and click Import Flat File above Import Data.


2 Answers

I would recommend looking at using SSIS. It's designed to do this sort of thing (especially if you need to do it on a regular basis).

Here is a good link that goes over reading a text file and inserting into the DB.

like image 120
Abe Miessler Avatar answered Oct 06 '22 21:10

Abe Miessler


If the file is ready to load "as-is" (no data transformations or complex mappings required), you can use the Bulk Insert command:

CREATE PROC dbo.uspImportTextFile

AS

BULK INSERT Tablename FROM 'C:\ImportFile.txt' WITH ( FIELDTERMINATOR ='|', FIRSTROW = 2 )

http://msdn.microsoft.com/en-us/library/ms188365.aspx

like image 21
brian Avatar answered Oct 06 '22 21:10

brian