Tuesday, July 22, 2014

Import CSV file into Microsoft SQL Server via SQL command

I find this method way easier than messing with SQL Server Import/Export Wizard.  Although it can be useful to have the wizard create the target table definition first.

CREATE TABLE [dbo].[TargetTable] (
    [Id] [int] NULL,
    [StringCol] [varchar](MAX) NULL,
    [IntCol] [int] NULL
    -- additional columns here
) ON [PRIMARY]
GO


BULK INSERT [dbo].[TargetTable]
    FROM 'C:\pathto\SourceFile.csv'
    WITH
    (
        FIRSTROW = 2,             -- 2 if there are headers
        FIELDTERMINATOR = ',',    -- field delimiter
        ROWTERMINATOR = '\n',     -- next row
        ERRORFILE = 'C:\pathto\_ImportErrors.txt',
        TABLOCK
    )
GO



No comments:

Post a Comment