在某些情况下,数据文件中包含的字段与表中对应列的顺序可能不同。例如,New_auth.dat 数据文件(ASCII 格式,即字符格式)与 authors2 表包含相同的字段数,但是 au_lname 和 au_fname 字段的次序相反。这两个字段在大容量复制过程中将重新排序。
New_auth.dat 文件的内容如下:
777-77-7777,Chris,Smith,303 555-1213,27 College Ave,Denver,CO,80220,1
888-88-8888,John,Doe,206 555-1214,123 Maple Street,Seattle,WA,95099,0
999-99-9999,Jane,Door,406 555-1234,45 East Main,Bozeman,MT,59715,1
若要将数据有选择地大容量复制到 authors2 的适当列中,请使用以下命令创建默认的格式文件 (Authors.fmt):
bcp pubs..authors2 out c:\authors.txt -Sservername -Usa -Ppassword
bcp 实用工具将提示输入 authors2 中每一列的文件存储类型、前缀长度、字段长度和字段终止符。每列的字段终止符均应为逗号 (,),但 contract 列除外,该列应使用行终止符 \n(换行符),因为该列是行中的最后一列。另外,因为该数据文件为 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™ 表所需的全部信息。不过,但是,需要使用文本编辑器进一步修改格式文件,以更改 au_lname 和 au_fname 字段的服务器列顺序(格式文件中的第六个字段)。
8.0 9 1 SQLCHAR 0 11 "," 1 au_id SQL_Latin1_General_Cp437_BIN 2 SQLCHAR 0 40 "," 3 au_lname SQL_Latin1_General_Cp437_BIN 3 SQLCHAR 0 20 "," 2 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
现在若要将该数据文件中的数据大容量复制到 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')