SQL查询从物理位置读取文件名和内容

问题描述 投票:0回答:1

我需要SQL查询或函数/过程,它可以从物理位置读取所有文件名和内容并插入到SQL表中。这里有两件事-

  1. 所有文件都是文本文件(.txt)

  2. 且文件名不能重复(需要在查询中添加条件)

我的桌子如下所示:

enter image description here

第一列(Id)是主键和标识列。第二列(File_Name)是存储文件名(不带扩展名),第三列(File_Content)是存储文件内容或数据。

我的文件目录或物理位置如下所示:

enter image description here

结果或 SQL 表数据应如下所示:

enter image description here

sql-server readfile
1个回答
0
投票

使用纯sql查询您无法访问文件和文件操作。您可能需要使用 Python 或 sehll 命令以及 sql 查询:

这是您如何读取临时表中的文件列表,然后复制到真正的 SQL 表中:

--Enabling xp_cmdshell 
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
EXEC sp_configure 'xp_cmdshell', 1;
RECONFIGURE;


-- Creating a temp table and list files
DECLARE @DirCommand NVARCHAR(MAX);
DECLARE @DirOutput TABLE (FileName NVARCHAR(50), FileContent NVARCHAR(MAX));
SET @DirCommand = 'DIR /B "C:\repository\*.txt"';
INSERT INTO #TempFiles (FileName, FileContent)
EXEC xp_cmdshell @DirCommand;

-- Copying data from temp table into a sql table
INSERT INTO YourTable (file_name, file_content)
SELECT FileName, FileContent FROM @DirOutput;

-- Disable xp_cmdshell to enhance security
EXEC sp_configure 'xp_cmdshell', 0;
RECONFIGURE;
© www.soinside.com 2019 - 2024. All rights reserved.