在某些情况下,数据文件包含的字段数可能多于表中的列数。例如,New_auth.dat 数据文件(ASCII 格式,即字符格式)包含 authors2 表中不包含的两个字段(age 和 salutation)。这两个字段将在大容量复制过程中忽略(即跳过)。
New_auth.dat 文件的内容如下:
777-77-7777,Smith,Chris,303 555-1213,27 College Ave,Denver,CO,80220,1,28,Ms.
888-88-8888,Doe,John,206 555-1214,123 Maple Street,Seattle,WA,95099,0,35,Mr.
999-99-9999,Door,Jane,406 555-1234,45 East Main,Bozeman,MT,59715,1,33,Mrs.
若要有选择地只将所需数据大容量复制到 authors2 的适当列中,请使用以下命令创建默认的格式文件 (Authors.fmt):
bcp pubs..authors2 out c:\authors.txt -Sservername -Usa -Ppassword
bcp 实用工具将提示输入 authors2 中每一列的文件存储类型、前缀长度、字段长度和字段终止符。每列的字段终止符均应为逗号 (,)。另外,因为该数据文件为 ASCII 文件,所以 contract 列的文件存储类型是 char。在提示输入格式文件名时,请指定 Authors.fmt。
Authors.fmt 文件的内容如下:
8.0 9 1 SQLCHAR 0 11 "," 1 au_id SQL_Latin1_General_Cp437_BIN 2 SQLCHAR 0 40 "," 2 au_lname SQL_Latin1_General_Cp437_BIN 3 SQLCHAR 0 20 "," 3 au_fname SQL_Latin1_General_Cp437_BIN 4 SQLCHAR 0 12 "," 4 phone SQL_Latin1_General_Cp437_BIN 5 SQLCHAR 0 40 "," 5 address SQL_Latin1_General_Cp437_BIN 6 SQLCHAR 0 20 "," 6 city SQL_Latin1_General_Cp437_BIN 7 SQLCHAR 0 2 "," 7 state SQL_Latin1_General_Cp437_BIN 8 SQLCHAR 0 5 "," 8 zip SQL_Latin1_General_Cp437_BIN 9 SQLCHAR 0 1 "
\r\n" 9 contract SQL_Latin1_General_Cp437_BIN
该格式文件包含将数据从数据文件大容量复制到 Microsoft® SQL Server™ 表所需的全部信息。但是,需要使用文本编辑器进一步修改格式文件,以反映新添加的两列:age 和 salutation。格式文件的第二行指定了列数,该列数现在应改为 11,因为数据文件中有 11 个字段。需要在格式文件的末尾添加两个新行,以便提供新增字段的格式信息。行终止符需要从 contract 列移到 salutation 列,age 和 salutation 列的服务器列号(格式文件中的第六个字段)应为 0:
8.0 11 1 SQLCHAR 0 11 "," 1 au_id SQL_Latin1_General_Cp437_BIN 2 SQLCHAR 0 40 "," 2 au_lname SQL_Latin1_General_Cp437_BIN 3 SQLCHAR 0 20 "," 3 au_fname SQL_Latin1_General_Cp437_BIN 4 SQLCHAR 0 12 "," 4 phone SQL_Latin1_General_Cp437_BIN 5 SQLCHAR 0 40 "," 5 address SQL_Latin1_General_Cp437_BIN 6 SQLCHAR 0 20 "," 6 city SQL_Latin1_General_Cp437_BIN 7 SQLCHAR 0 2 "," 7 state SQL_Latin1_General_Cp437_BIN 8 SQLCHAR 0 5 "," 8 zip SQL_Latin1_General_Cp437_BIN 9 SQLCHAR 0 1 "," 9 contract SQL_Latin1_General_Cp437_BIN 10 SQLCHAR 0 0 "," 0 age SQL_Latin1_General_Cp437_BIN 11 SQLCHAR 0 0 "
\r\n" 0 salutation SQL_Latin1_General_Cp437_BIN
现在若要将该数据文件中的数据大容量复制到 authors2 中,可以使用以下命令:
bcp pubs..authors2 in c:\new_auth.dat -fc:\authors.fmt -Sservername -Usa -Ppassword
另外,也可以在 SQL 查询分析器这样的查询工具中使用 BULK INSERT 语句来大容量复制数据:
BULK INSERT pubs..authors2 FROM 'c:\new_auth.dat'
WITH (FORMATFILE = 'c:\authors.fmt')