CREATE TABLE [dbo].[tblUser](
[UserID] [nvarchar](36) NOT NULL,
[LoginID] [nvarchar](20) NOT NULL,
[UserName] [nvarchar](50) NULL,
[Password] [nvarchar](200) NULL,
[DateCreated] [datetime] NULL,
[CreatedBy] [nvarchar](36) NULL,
[DateLastupdated] [datetime] NULL,
[LastupdatedBy] [nvarchar](36) NULL,
[CompanyID] [nvarchar](36) NULL,
[DeparementID] [nvarchar](36) NULL,
[IsEnable] [char](1) NULL,
CONSTRAINT [PK_tblUser] PRIMARY KEY NONCLUSTERED
(
[UserID] ASC,
[LoginID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
上面是表结构。
BCP导出导入如下命令
exec xp_cmdshell 'bcp sony.dbo.tblUser out c:\tblUser_data.txt -c -UUserName -PPassword -S ServerName,1433'
--导出数据到文本文件
exec xp_cmdshell 'bcp sony.dbo.tblUser in c:\tblUser_data.txt -c -UUserName -PPassword -S ServerName,1433'
--从文本文件导入到db
exec xp_cmdshell 'bcp "select top 1 * from sony.dbo.tblUser" queryout c:\tblUser_data.txt -c -q -UUserName -PPassword -S ServerName,1433'
--导出查询结果到文本文件
exec xp_cmdshell 'bcp "select top 1 * from sony.dbo.tblUser" queryout c:\tblUser_data.txt -c -T'
--使用信任连接导出数据到文本文件
exec xp_cmdshell 'bcp sony.dbo.tblUser format nul -t """,""" -f c:\tblUser.fmt -c -UUserName -PPassword -S ServerName,1433'
format nul -- 这里的nul必须存在,用于不是导出和导入数据的情况下
-f 输出的格式化文件名 [-x] -c -- -x参数指定输出的格式文件为xml格式(默认非xml格式); -c参数指定数据
存储方式为字符,并默认指定'\t'作为字段间隔符;'\n'作为行间隔符
[-t 字段间隔符] [-r 行间隔符号] -- -t与-r参数可选,用于覆盖-c指定的默认间隔符
-T -- 指定数据库连接可信,即使用Windows身份登录
insert into tblUser
select *
from
openrowset(bulk 'c:\tblUser.csv', --要读取的文件路径和名称
formatfile='c:\tblUser.fmt', --格式化文件的路径和名称
firstrow = 1, --要载入的第一行,由于第一行是标题,所以从2开始
lastrow = 1000, --要载入的最后一行,此值必须大于firstrow
maxerrors = 10, --在加载失败之前加载操作中最大的错误数
errorfile ='c:\wc_error1.txt', --存放错误的文件
rows_per_batch = 10000 --每个批处理导入的行数
) as t
bulk insert tblUser
from 'c:\tblUser.csv'
with(fieldterminator='\",\"',
firstrow=1,
rowterminator='\n')
这种情况也能正常插入数据,但是和opendrowset 稍有区别。
当文本文件中保存的每行数据开头结尾都有双引号(如下)的话,那么只有openrowset能够正常识别字符串。
"C2F8DF44-5CD7-48D6-980C-8F6E9AC31251","0000000001","ad"min,admin","1234","2018-05-26 09:43:08.303","SYSTEM","2018-05-26 09:43:08.303","SYSTEM","NULL","NULL","1"
当文本文件中保存的每行数据开头结尾没有双引号(如下)的话,那么openrowset 和 bulk insert 都能正常插入数据。
C2F8DF44-5CD7-48D6-980C-8F6E9AC31251","0000000001","ad"min,admin","1234","2018-05-26 09:43:08.303","SYSTEM","2018-05-26 09:43:08.303","SYSTEM","NULL","NULL","1