Monday, January 30, 2012

Uploading a lot data using single T-SQL query

You need a MS SQL database with a lot of data, and you have those data on separated file as a .csv file, then you could use a bulk insert to make this task using single query like:

bulk insert myDB..myTable from "t:\mydata\mydata.csv" with (FieldTerminator = ',', FirstRow =2)

Then the first part parameter of “bulk insert” should our table that need have a lot of data, the second parameter is the file with our data and the last parameter is the string used to delimitate. Think our data could be:

10,01:50,10,Place010,Room10,Printer0010

In this our sample our table will have six columns: ID,Hour,IDemp,Place,Room,Printer.

A sample file with 10.000 records can be found in: myData.csvimage

and sample to create the Database and table below:

/*Create myDB*/

CREATE DATABASE [myDB]

CONTAINMENT = NONE

ON PRIMARY

( NAME = N'myDB', FILENAME = N'T:\mySQL2012\DATA\myDB.mdf' , SIZE = 3072KB , FILEGROWTH = 1024KB )

LOG ON

( NAME = N'myDB_log', FILENAME = N'T:\mySQL2012\DATA\myDB_log.ldf' , SIZE = 1024KB , FILEGROWTH = 10%)

GO

/*Create myTable*/

CREATE TABLE [dbo].[myTable](

[ID] [nchar](10) NULL,

[Hour] [time](7) NULL,

[IDemp] [nchar](10) NULL,

[Place] [nchar](10) NULL,

[Room] [nchar](10) NULL,

[Printer] [nchar](15) NULL

) ON [PRIMARY]

GO

No comments: