Thursday, July 8, 2010

Import CSV File using SQL Query

SQL Query :

DECLARE @FileName VARCHAR(100) = 'C:\EmployeeInfo.csv'

CREATE TABLE #UserInfo
(
UserName VARCHAR(50)
, Address VARCHAR(100)
, CITY VARCHAR(10)
)

/*** Get Data From Import File ***/
DECLARE @SqlQuery VARCHAR(2000)
SELECT @SqlQuery = 'BULK INSERT'
+ ' #UserInfo'
+ ' FROM'
+ ' ''' + @FileName + ''' '
+ ' WITH (FIELDTERMINATOR='','''
+ ',ROWTERMINATOR = ''' + CHAR(10) + ''')'

EXECUTE ( @SqlQuery )
/*** Get Data From Import File ***/

SELECT * FROM #UserInfo

DROP TABLE #UserInfo
CSV File :
Eugene Malarky,Grove Street Smithtown,New York
Sam Adams,Main Street,Ashville
Loren Sandler,Main Street,Hometown
Output :
UserName                       Address                        CITY
------------------------------ ------------------------------ ----------
Eugene Malarky Grove Street Smithtown New York

Sam Adams Main Street Ashville

Loren Sandler Main Street Hometown

No comments: