I’m going to go over some methods to import data from text files into SQL Server today. The particular file I went out and grabbed is comma delimited and with a few qualifiers in it. It is a typical file you may get and a request made to import or just for your own administrative tasks.

Below is the location of field layout and file that I grabbed off the net to play with. This is just a text file comma separated of zip codes. I will attach the file as well to this blog.

http://spatialnews.geocomm.com/newsletter/2000/jan/zipcodes.html

Field 1 – State Fips Code
Field 2 – 5-digit Zipcode
Field 3 – State Abbreviation
Field 4 – Zipcode Name
Field 5 – Longitude in Decimal Degrees (West is assumed, no minus sign)
Field 6 – Latitude in Decimal Degrees (North is assumed, no plus sign)
Field 7 – 1990 Population (100%)
Field 8 – Allocation Factor (decimal portion of state within zipcode)

Example of file

Import Wizard

First and very manual technique is the import wizard. This is great for ad-hoc and just to slam it in tasks.

In SSMS right click the database you want to import into. Scroll to Tasks and select Import Data…

For the data source we want out zips.txt file. Browse for it and select it. You should notice the wizard tries to fill in the blanks for you. One key thing here with this file I picked is there are “ “ qualifiers. So we need to make sure we add “ into the text qualifier field. The wizard will not do this for you.

Go through the remaining pages to view everything. No further changes should be needed though

Hit next after checking the pages out and select your destination. This in our case will be DBA.dbo.zips.

Following the destination step, go into the edit mappings section to ensure we look good on the types and counts.

Hit next and then finish. Once completed you will see the count of rows transferred and the success or failure rate

Import wizard completed and you have the data!

bcp utility

Method two is bcp with a format file http://msdn.microsoft.com/en-us/library/ms162802.aspx

This is probably going to win for speed on most occasions but is limited to the formatting of the file being imported. For this file it actually works well with a small format file to show the contents and mappings to SQL Server.

To create a format file all we really need is the type and the count of columns for the most basic files. In our case the qualifier makes it a bit difficult but there is a trick to ignoring them. The trick is to basically throw a field into the format file that will reference it but basically ignore it in the import process.

Given that our format file in this case would appear like this

  1. 9.0
  2. 9
  3. 1 SQLCHAR 0 0 """ 0 dummy1 ""
  4. 2 SQLCHAR 0 50 "","" 1 Field1 ""
  5. 3 SQLCHAR 0 50 "","" 2 Field2 ""
  6. 4 SQLCHAR 0 50 "","" 3 Field3 ""
  7. 5 SQLCHAR 0 50 ""," 4 Field4 ""
  8. 6 SQLCHAR 0 50 "," 5 Field5 ""
  9. 7 SQLCHAR 0 50 "," 6 Field6 ""
  10. 8 SQLCHAR 0 50 "," 7 Field7 ""
  11. 9 SQLCHAR 0 50 "n" 8 Field8 ""

The bcp call would be as follows

C:Program FilesMicrosoft SQL Server90ToolsBinn>bcp DBA..zips in “C:zips.txt” -f “c:zip_format_file.txt” -S LKFW0133 -T

Given a successful run you should see this in command prompt after executing the statement

  1. Starting copy...
  2. 1000 rows sent to SQL Server. Total sent: 1000
  3. 1000 rows sent to SQL Server. Total sent: 2000
  4. 1000 rows sent to SQL Server. Total sent: 3000
  5. 1000 rows sent to SQL Server. Total sent: 4000
  6. 1000 rows sent to SQL Server. Total sent: 5000
  7. 1000 rows sent to SQL Server. Total sent: 6000
  8. 1000 rows sent to SQL Server. Total sent: 7000
  9. 1000 rows sent to SQL Server. Total sent: 8000
  10. 1000 rows sent to SQL Server. Total sent: 9000
  11. 1000 rows sent to SQL Server. Total sent: 10000
  12. 1000 rows sent to SQL Server. Total sent: 11000
  13. 1000 rows sent to SQL Server. Total sent: 12000
  14. 1000 rows sent to SQL Server. Total sent: 13000
  15. 1000 rows sent to SQL Server. Total sent: 14000
  16. 1000 rows sent to SQL Server. Total sent: 15000
  17. 1000 rows sent to SQL Server. Total sent: 16000
  18. 1000 rows sent to SQL Server. Total sent: 17000
  19. 1000 rows sent to SQL Server. Total sent: 18000
  20. 1000 rows sent to SQL Server. Total sent: 19000
  21. 1000 rows sent to SQL Server. Total sent: 20000
  22. 1000 rows sent to SQL Server. Total sent: 21000
  23. 1000 rows sent to SQL Server. Total sent: 22000
  24. 1000 rows sent to SQL Server. Total sent: 23000
  25. 1000 rows sent to SQL Server. Total sent: 24000
  26. 1000 rows sent to SQL Server. Total sent: 25000
  27. 1000 rows sent to SQL Server. Total sent: 26000
  28. 1000 rows sent to SQL Server. Total sent: 27000
  29. 1000 rows sent to SQL Server. Total sent: 28000
  30. 1000 rows sent to SQL Server. Total sent: 29000

bcp import completed!

BULK INSERT

Next, we have BULK INSERT given the same format file from bcp

  1. CREATE TABLE zips (
  2. Col1 nvarchar(50),
  3. Col2 nvarchar(50),
  4. Col3 nvarchar(50),
  5. Col4 nvarchar(50),
  6. Col5 nvarchar(50),
  7. Col6 nvarchar(50),
  8. Col7 nvarchar(50),
  9. Col8 nvarchar(50)
  10. );
  11. GO
  12. INSERT INTO zips
  13. SELECT *
  14. FROM OPENROWSET(BULK 'C:Documents and SettingstkruegerMy Documentsblogcenzuszipcodeszips.txt',
  15. FORMATFILE='C:Documents and SettingstkruegerMy Documentsblogzip_format_file.txt'
  16. ) as t1 ;
  17. GO

That was simple enough given the work on the format file that we already did. Bulk insert isn’t as fast as bcp but gives you some freedom from within TSQL and SSMS to add functionality to the import.

SSIS

Next is my favorite playground in SSIS

We can do many methods in SSIS to get data from point A, to point B. I’ll show you data flow task and the SSIS version of BULK INSERT

First create a new integrated services project.

Create a new flat file connection by right clicking the connection managers area. This will be used in both methods

Bulk insert

You can use format file here as well which is beneficial to moving methods around. This essentially is calling the same processes with format file usage. Drag over a bulk insert task and double click it to go into the editor.

Fill in the information starting with connection. This will populate much as the wizard did.

Example of format file usage

Or specify your own details

Execute this and again, we have some data

Data Flow method

Bring over a data flow task and double click it to go into the data flow tab.

Bring over a flat file source and SQL Server destination. Edit the flat file source to use the connection manager “The file” we already created. Connect the two once they are there

Double click the SQL Server Destination task to open the editor. Enter in the connection manager information and select the table to import into.

Go into the mappings and connect the dots per say

Typical issue of type conversions is Unicode to non-unicode.

We fix this with a Data conversion or explicit conversion in the editor. Data conversion tasks are usually the route I take. Drag over a data conversation task and place it between the connection from the flat file source to the SQL Server destination.

New look in the mappings

And after execution…

SqlBulkCopy Method

Sense we’re in the SSIS package we can use that awesome “script task” to show SlqBulkCopy. Not only fast but also handy for those really “unique” file formats we receive so often

Bring over a script task into the control flow

Double click the task and go to the script page. Click the Design script to open up the code behind

Go ahead and put this code into the task.

  1. Imports System
  2. Imports System.Data
  3. Imports System.Math
  4. Imports System.Xml
  5. Imports System.Data.SqlClient
  6. Imports System.Data.OleDb
  7. Imports Microsoft.SqlServer.Dts.Runtime
  8.  
  9. Public Class ScriptMain
  10.  
  11. Public Sub Main()
  12. Dim conn As New SqlConnection("Data Source=LKFW0133;Initial Catalog=DBA;Integrated Security=SSPI")
  13.  
  14. Using bulk As New SqlBulkCopy(conn.ConnectionString)
  15. bulk.BatchSize = 1000
  16. bulk.NotifyAfter = 1000
  17. bulk.DestinationTableName = "zips"
  18. AddHandler bulk.SqlRowsCopied, AddressOf OnSqlRowsCopied
  19. bulk.WriteToServer(LoadupDTFromTxt)
  20. End Using
  21.  
  22. Dts.TaskResult = Dts.Results.Success
  23. End Sub
  24.  
  25. Private Sub OnSqlRowsCopied(ByVal sender As Object, _
  26. ByVal args As SqlRowsCopiedEventArgs)
  27. Console.WriteLine("Copied {0} so far...", args.RowsCopied)
  28. End Sub
  29.  
  30. Private Function LoadupDTFromTxt() As DataTable
  31. Dim cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:;Extended Properties=""Text;HDR=No;FMT=Delimited""")
  32. Dim da As New OleDbDataAdapter()
  33. Dim ds As New DataSet
  34. Dim cd As New OleDbCommand("SELECT * FROM C:zips.txt", cn)
  35. cn.Open()
  36. da.SelectCommand = cd
  37. ds.Clear()
  38. da.Fill(ds, "zips")
  39. Return ds.Tables(0)
  40. cn.Close()
  41. End Function
  42. End Class

Then execute the script task

Again the same results as previous methods but with a new look.

All of these methods have a place in each unique situation. Performance wise in my experience, bcp wins on speed typically. This is not always a method you can use though which leads us to other resources SQL Server and services provide us.

Of course none of this would be completely finished unless we added some statistics on runtimes along with these methods. I went ahead and created 3 addition zips.txt files to go with the original. In these files we have the following

zips.txt – 29,471 rows at around 1.8MB
zips_halfmill.txt – 500,991 rows at around 31.4MB
zips_million.txt – 1,001,981 rows at around 62.8MB
zips_5mill.txt – 5,009,901 rows and around 314.3MB

I ran these each through all the methods. My results are below. Mind you, the important thing to understand is that I write my blogs/articles off my eprsonal test lab. In no way do I utilize monster servers that would be more suited for benchmarking each. All hardware is created not so equal and results will be varying given that variable. Take these results but keep in mind that resources will make them move up and down the chart. Memory, I/O and CPU is a big factor in speed.

Tests were complete by running each process 5 times. All resources cleared on each execution.
Shown in AVG of milliseconds between the types. Import Wizard was not tested as this is basically a Data Flow Task behind the scenes and can be seen (minus the slow user clicking things) from the Data Flow Task in SSIS results

Hope this helps as a good reference in your own imports.

About the Author

Ted Krueger is a SQL Server MVP and has been working in development and database administration for 13+ years. Specialties range from High Availability and Disaster / Recovery setup and testing methods down to custom assembly development for SQL Server Reporting Services. Ted blogs and is also one of the founders of LessThanDot.com technology community. Some of the articles focused on are Backup / Recovery, Security, SSIS and working on SQL Server and using all of the SQL Server features available to create stable and scalable database services. @onpnt Personal Blog over at http://onpnt.wordpress.com/

6 ways to import data into SQL Server的更多相关文章

  1. Transfer data to SQL Server from SPC-Light with Excel macros

    公司的QA检测软件SPC-Light,需要从其中读取一些信息至SQL Server数据库,储存或是做其它分析. 先是在Excel的VBE的工具中,引入一个组件Microsoft ActiveX Dat ...

  2. Data Base sql server 备份数据库

    sql server 备份数据库 1.维护计划向导: 右键维护计划-维护计划向导-然后安装提示: 勾选自己要干的事,比如:完整备份数据库.差异备份数据库等等 2.作业计划: 如下图: SQL Serv ...

  3. [MSSQL2008]Spatial Data in SQL Server 2008 - 根据经纬度计算两点间距离

    DECLARE @BJ GEOGRAPHY DECLARE @XT GEOGRAPHY /*     GET Latitude/Longitude FROM here:http://www.trave ...

  4. BCP command usage in SQL Server

    The bcp Command-Line Utility You use the bcp (bulk copy program) tool to address the bulk movement o ...

  5. Microsoft SQL Server Version List [sqlserver 7.0-------sql server 2016]

    http://sqlserverbuilds.blogspot.jp/   What version of SQL Server do I have? This unofficial build ch ...

  6. Microsoft SQL Server Version List(SQL Server 版本)

    原帖地址 What version of SQL Server do I have? This unofficial build chart lists all of the known Servic ...

  7. 《Pro SQL Server Internals, 2nd edition》的CHAPTER 1 Data Storage Internals中的Data Pages and Data Rows(翻译)

    数据页和数据行 数据库中的空间被划分为逻辑8KB的页面.这些页面是以0开始的连续编号,并且可以通过指定文件ID和页号来引用它们.页面编号都是连续的,这样当SQL Server增长数据库文件时,从文件中 ...

  8. Migrating Oracle on UNIX to SQL Server on Windows

    Appendices Published: April 27, 2005 On This Page Appendix A: SQL Server for Oracle Professionals Ap ...

  9. Integrating .NET Code and SQL Server Reporting Services

    SQL Server Reporting Services versions 2000 and 2005 (SSRS) has many powerful features. SSRS has a w ...

随机推荐

  1. Memory Leak检測神器--LeakCanary初探

      在之前的文章Android内存泄露的几种情形中提到过在开发中常见的内存泄露问题,可是过于草率.因为刚开年,工作还没正式展开,就看了一下Github开源大户Square的LeakCanary,并用公 ...

  2. linux:文件及文件夹管理

    http://blog.csdn.net/pipisorry/article/details/39854265 查看用户的信息 pika:~$id pikauid=1000(pika) gid=100 ...

  3. EditText: 自定义EditText 触摸时无法获取焦点

    写了一个自定义View,继承EditText,但是在触摸时无法获取到焦点. 在XML中添加 android:focusableInTouchMode="true" 设置触摸时可以获 ...

  4. android笔记---主界面(二)自定义actionbar环境的配置

    第一步,添加java文件 第二步,添加actionbar的item文件 是个选择器,点中状态和选中状态 <?xml version="1.0" encoding=" ...

  5. java 多线程 25 :线程和线程组的异常处理

    线程中出现异常 从上面代码可以看出来处理线程的异常 设置异常的两种方式 1.全局异常,也是静态异常,是个静态方法 , 类.setDefaultUncaughtExceptionHandler() 2. ...

  6. Python爬网——获取安卓手机统计数据

    [本文出自天外归云的博客园] 1. 在安卓网上对热门机型进行爬网,取前五十: # -*- coding: utf-8 -*- import requests,re from bs4 import Be ...

  7. Python操作SQLAlchemy之连表操作

    多对一连表操作 首先有两个知识点: 改变数据输出的方式:可以在表的类中定义一个特殊成员:__repr__,return一个自定义的由字符串拼接的数据连接方式. 数据库中表关系之间除了MySQL中标准的 ...

  8. 移动web开发(二)——viewport

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scal ...

  9. JAVA-JSP内置对象

    相关资料:<21天学通Java Web开发> request 请求对象 类型javax.servlet.ServletRequest 作用域Requestresponse 响应对象 类型j ...

  10. [转]为Kindeditor控件添加图片自动上传功能

    原文地址:http://www.cnblogs.com/jaxu/p/3824583.html Kindeditor是一款功能强大的开源在线HTML编辑器,支持所见即所得的编辑效果.它使用JavaSc ...