[转]How to Import a Text File into SQL Server 2012

Importing a Text File into SQL Server 2012 using the OpenRowSet() Function

The OPENROWSET bulk row set provider is accessed by calling the OPENROWSET function and specifying the BULK option. The OPENROWSET(BULK…) function allows you to access remote data by connecting to a remote data source, such as a data file, through an OLE DB provider.

To bulk import data, call OPENROWSET(BULK…) from a SELECTFROM clause within an INSERT statement. The basic syntax for bulk importing data is:

INSERTSELECT * FROM OPENROWSET(BULK…)

When used in an INSERT statement, OPENROWSET(BULK…) supports table hints. In addition to the regular table hints, such as TABLOCK, the BULK clause can accept the following specialized table hints: IGNORE_CONSTRAINTS (ignores only the CHECK constraints), IGNORE_TRIGGERS, KEEPDEFAULTS, and KEEPIDENTITY.

This example imports text file into SQL-Server 2012 using OpenRowSet command.

Step 1) Create a Data Table (corresponding to columns in text file)

CREATE TABLE [dbo].[players](
     [RK] [varchar](50) NULL,
     [PLAYER] [varchar](50) NULL,
     [Salary (US$)] [varchar](50) NULL
 ) ON [PRIMARY]

Step 2) Create a Format File Specific to Text File

  The file is using SQL Server edition 11.0 (i.e. SQL Server 2012)
       Table has 3 columns.
       Each column can accept 0 to 50 chars.
       Each column is tab separated \t.
       Each new row is separated by new line char \r\n.

Players.fmt

11.0
 3
 1       SQLCHAR             0       50      “\t”   1     RK                           Latin1_General_CI_AI
 2       SQLCHAR             0       50      “\t”   2     PLAYER                       Latin1_General_CI_AI
 3       SQLCHAR             0       50      “\r\n”   3     Salary                Latin1_General_CI_AI

Step 3) Test OpenRowSet Command

Select document.* from openrowset(BULK N’C:\players.txt’,formatfile=N’c:\player.fmt’ ,firstrow=2) as document.

Step 4) Insert into Players Datatable

Insert into [dbo].[players]
 select document.* from openrowset(BULK N’C:\players.txt’,formatfile=N’c:\players.fmt’,firstrow=2) as document

Players.txt

RK           PLAYER                 Salary
 1         Alex Rodriguez         30,000,000
 2        CC Sabathia                24,285,714
 3        Mark Teixeira           23,125,000
 4        Ichiro Suzuki            18,000,000
 5        Derek Jeter               15,729,365
 6        Mariano Rivera       14,940,025
 7        Robinson Cano        14,000,000

Step 5) Verify Data in Players 

Select * from dbo.players

For more Microsoft Technical Training information visit www.directionstraining.com or call 1-855-575-8900.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值