使用的为sqlserver2017版本
一、xp_cmdshell组件不能用
报错提示:
“ 消息 15281,级别 16,状态 1,过程 xp_cmdshell,第 1 行 SQL Server 阻止了对组件
‘xp_cmdshell’ 的 过程’sys.xp_cmdshell’
的访问,因为此组件已作为此服务器安全配置的一部分而被关闭。系统管理员可以通过使用 sp_configure 启用
‘xp_cmdshell’。有关启用 ‘xp_cmdshell’ 的详细信息,请参阅 SQL Server 联机丛书中的
“外围应用配置器”. ”
解决方法:
--执行以下语句
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
EXEC sp_configure 'xp_cmdshell', 1
RECONFIGURE
二、判断某个路径下的某个文件是否存在
--判断文件是否存在
declare @errCode varchar(2)
EXEC @errCode = master..xp_cmdshell 'dir D:\If_paths.txt'
select @errCode --存在的话返回0 不存在返回1
三、判断临时表是否存在
--判断临时表是否存在
declare @sss varchar(10)
if exists (select * from tempdb.dbo.sysobjects where id = object_id(N'tempdb..#表名') and type='U')
begin
set @sss = '存在'
drop table #表名 --删除临时表
end
else
begin
set @sss = '不存在'
end
四、创建临时表并读取执行文件中的数据插入到临时表中(逐行读取)
①只有一列数据
【文档内容】
【SQL语句】
--创建临时表
declare @cmd varchar(1000)
create table #TEST_TABLE
(
file_value char(100)
)
--从txt文件中按行读取数据,插入到临时表中
set @cmd ='bulk insert #TEST_TABLE from ''D:\1234.txt'' WITH( FIELDTERMINATOR = ''\t'', ROWTERMINATOR = ''\n'')'
exec (@cmd)
--查询临时表
select * from #TEST_TABLE
【执行结果】
PS:遇到个问题就是我的 txt文本格式是UTF-8的时候,读取插入表中是乱码:
【文档内容】
执行结果:
文本格式改为ANSI的时候读入正常。
②插入多列
文档内容:
【SQL语句】
--判断临时表是否存在,存在就删除
if exists (select * from tempdb.dbo.sysobjects where id = object_id(N'tempdb..#table') and type='U')
begin
drop table #table
end
--创建存储过程--后面挪到主存储过程中
create table #table
(
one varchar(50),
two varchar(50),
three varchar(50)
)
--定义需要用到的变量
declare @path varchar(255) = '',
@地址 varchar(100),
@文件名 varchar(100),
@cmd varchar(255)
--变量赋值
set @地址 = 'E:'
set @文件名 = 'wendang.csv'
set @path =@地址 + '\' + @文件名
--执行读取插入
set @cmd ='bulk insert #table from '''+@path + ''' WITH( FIELDTERMINATOR = '','', ROWTERMINATOR = ''\n'',FIRSTROW = 2,KEEPNULLS)'
exec (@cmd)
select * from #table
【执行结果】
五、取指定行的数据
--取第一行数据,并赋值
select top