Solved

Inserting multiple CSV files into SQL server

Posted on 2016-09-12
6
50 Views
Last Modified: 2016-09-14
I have about 1000 files that I need to import into a table in SQL.  Are there any tools out there to make this easier?
If not, what's the best way?

Currently using SQL Express 2012.
0
Comment
Question by:Brian Sandt
6 Comments
 
LVL 65

Expert Comment

by:Jim Horn
ID: 41794894
SSIS has a ForEach File Loop container where you can point to a specific folder and loop through every file in the folder.  Then inside this container you can add a Data Flow Task that consumes the file in the loop as the source, and have your table as the destination.

This assumes that the 1000 files have exactly the same file specs.
0
 

Author Comment

by:Brian Sandt
ID: 41794904
From what I've read, Express doesn't support SSIS.
0
 
LVL 35

Expert Comment

by:[ fanpages ]
ID: 41794905
Hi,

Sorry for the copy'n'paste of external links, but I thought going straight to the "horse's mouth" may be better for your background reading:

"Import and Export Bulk Data by Using the bcp Utility (SQL Server)" (MS-SQL Server 2012)
[ https://msdn.microsoft.com/en-gb/library/aa337544(v=sql.110).aspx ]

"bcp Utility" (MS-SQL Server 2012)
[ https://msdn.microsoft.com/en-gb/library/ms162802(v=sql.110).aspx ]

Also, unless already set in your version of MS-SQL Server 2012 Express:

"View or Configure Remote Server Connection Options"
[ https://msdn.microsoft.com/en-us/library/ms179383(v=sql.110).aspx ]
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 26

Expert Comment

by:Zberteoc
ID: 41795006
Do all those files have the same data structure in them? If that is the case then it is easy:

1. Create the table with the corresponding structure where the data from the files will be imported. If you are not sure of the data types for the fields then using a generic NVARCHAR will make sure it will "swallow" anything you might encounter.

2. Create a list with all the files you have in the folder. If they are in different folders it is better to copy them in one.

3. Use the list to create the BCP commands that will take each file in the list and will import it into the table created at step 1. This can be done easily in a batch file that will be executed on any machine on the same network with the target SQL server that has BCP installed on it. Can be the SQL server itself. BCP is a command line utility that comes together with the SQL server installation and it is the fastest tool there is when it comes to importing files.
0
 
LVL 40

Accepted Solution

by:
lcohan earned 500 total points
ID: 41795057
Here is what I use to restore DB backups and adapted for your CSV import. Just make the few changes to put your actual Path, YourFileNameHere, YourTableNameHere, etc and you can safely run the script below at it will only print the commands until you will uncomment the EXEC line at the bottom.

I would suggest to try it against a copy of the actual table to make sure ALL rows from ALL files go in there safely first.

to enable the xp_cmdshell you can run commands:

--Enable xp_cmdshell

exec sp_configure 'show advanced options', 1;
GO
sp_configure 'xp_cmdshell', 1;
GO
RECONFIGURE WITH OVERRIDE;
GO
sp_configure
GO


---script to import N CSV's into a table

declare @sqlstr nvarchar(max);
declare @restdb nvarchar(max);
declare @i table (col1 varchar(max) null);
declare @fn varchar(255);
set nocount on;

set @sqlstr = N'exec master..xp_cmdshell ''dir C:\FullPathHere\YourFileNameHere.csv /o-d'''

insert @i execute sp_executesql @sqlstr

--you have all files listed in @i table
--select * from @i where col1 like '%.csv'

-- start a loop here to go through all files to restore
WHILE EXISTS (select top 1 * from @i where col1 like '%.csv')
BEGIN -- loop

            --lets get the first one - you need to to a bit of string parsing to get the filename
            --select top 1 * from @i where col1 like '%.csv'
            set @fn = (select top 1 substring(col1, PATINDEX('%YourFileNameHere%',col1), datalength(col1) - PATINDEX('%YourFileNameHere%',col1)+1) from @i where col1 like '%.csv');
            print @fn;

            --build the command string to be executed - insert in your case
            SET @restdb =
            'BULK INSERT YourTableNameHere
            FROM ' + @fn +
            ' WITH
            (
            FIELDTERMINATOR = '','',
            ROWTERMINATOR = ''\n''
            )';

            print @restdb;
            --exec sp_executesql @restdb;      -- *****!!!! uncomment this line and comment all PRINT command lines to perform the actual statemet instead of just print on screen
            if @@ERROR <> 0 BREAK;

            -- delete the file we just procesed so is not done again in the loop
            delete @i where col1 like @fn;

END -- loop
GO
0
 
LVL 26

Expert Comment

by:Zberteoc
ID: 41797822
@lcohan

It is better if you post any code within the code tag.
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Introduction In my previous article (http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/SSIS/A_9150-Loading-XML-Using-SSIS.html) I showed you how the XML Source component can be used to load XML files into a SQL Server database, us…
Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

735 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question