我正在Microsoft Windows 10上使用SQL Server 2017 Express版。我想一次将目录中的所有文本文件导入数据库。我的想法是,SQL Server遍历该目录中的文件并同时将它们全部导入。有什么办法可以做到这一点?
最好的问候
答案 0 :(得分:0)
declare @dir varchar(1000) = 'C:\Temp';
declare @command varchar(1000);
declare @files table (id int identity, filename varchar(1000));
set @command = 'dir /b ' + @dir;
insert into @files execute xp_cmdshell @command;
declare commands cursor for
select 'bulk insert <your table name here> from ''' + @dir + '\' + filename + ''' <other options, WITH FORMAT, etc. here>;' from @files;
open commands;
fetch commands into @command;
while (@@fetch_status = 0) begin
--print @command;
execute(@command);
fetch commands into @command;
end;
close commands;
deallocate commands;
修改@dir和正在构建的大容量插入命令,您已完成。
您可能必须启用'xp_cmdshell',这对于您的DBA可能是个问题;并且使用“执行”始终是一个潜在的问题(SQL注入等)。
启用xp_cmdshell:
-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1;
GO
-- To update the currently configured value for advanced options.
RECONFIGURE;
GO
-- To enable the feature.
EXEC sp_configure 'xp_cmdshell', 1;
GO
-- To update the currently configured value for this feature.
RECONFIGURE;
GO
答案 1 :(得分:0)
如另一个答案中所述,function readdirAsync(path) {
return new Promise((resolve, reject) => {
fs.readdir(path, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
}).then(res => {
const versions = res.map(filename => match(/^[\d]+(\.+\d+)+/g, filename)[0]);
return versions;
});
}
async function getVersions() {
const final = await readdirAsync(require('path').join('src/versions/'));
return final;
}
const versionsList = getVersions().then(res => res);
console.log(versionsList);
是有问题的。 SQL Server 2016+允许另一种方法。参见示例
xp_commandshell