Import CSV into SQL2008 using TSQL

Experts,
I have a need to import a csv file that has the first row as column names into a table in an SQL2008 database. This must be done through the use of TSQL. This table will contain over 100 columns. The destination table column datatypes are pretty varied.

This could be done with a dtsx package that is executed from TSQL however I am running into truncation validation issues with most of the datatypes of the columns.

Thanks in advance!
TC72
TC72Asked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
Mohed SharfiConnect With a Mentor Vice CEOCommented:
Hi TC72,
How are you doing,to do this Please try this Example T-SQL(Snnipet) to  import from a csv file.
thanks
SELECT cast(field1 as bigint) as field1,cast(field2 as varchar(15)) as field2 
INTO dbo.file1table2
FROM 
OPENROWSET('MSDASQL','Driver={Microsoft Text Driver (*.txt; *.csv)};
DefaultDir=X:\;', 
'SELECT * from X:\Test\Import_OpenRowset.csv')
Select * from dbo.file1table2;

Open in new window

0
 
TC72Author Commented:
Thank you for your quick reply!

This worked well after enabling 'Ad Hoc Queries' on the DB instance.
0
All Courses

From novice to tech pro — start learning today.