我想编写一个存储过程,以便我可以执行一些我保存在特定文件夹中的SQL脚本。我已经提到过几篇文章,其中没有一篇能给我一个明确的答案。任何人都可以给我任何建议吗?
答案 0 :(得分:1)
显然,SQL帐户需要对这些文件/文件夹的访问权限。
DECLARE @FileContents VARCHAR(MAX)
SELECT @FileContents=BulkColumn
FROM OPENROWSET(BULK'PathToYourFile.sql', SINGLE_BLOB) x;
EXECUTE(@FileContents)
让它变得更有动态':
DECLARE @path nvarchar(MAX)
DECLARE @FileContents varchar(MAX)
SET @path = N'C:\Users\username\Desktop\example.txt'
SET @path = REPLACE(@path, N'''', N'''''')
DECLARE @sql nvarchar(MAX)
SET @sql = N'SELECT @FileContents=BulkColumn FROM OPENROWSET(BULK''' + @path + ''', SINGLE_BLOB) x;'
EXEC sp_executesql @sql, N'@FileContents varchar(MAX) OUTPUT', @FileContents=@FileContents OUTPUT;
EXECUTE(@FileContents);
<强>更新强> 您可以在以下目录中列出文件:
DECLARE @BasePath varchar(8000)
SET @BasePath = 'D:\temp'; -- List contents of this directory
--Create a temp table to hold the results.
IF OBJECT_ID('tempdb..#DirectoryTree')IS NOT NULL
DROP TABLE #DirectoryTree;
CREATE TABLE #DirectoryTree
(
id int IDENTITY(1,1)
,fullpath varchar(2000)
,subdirectory nvarchar(512)
,depth int
,isfile bit
);
INSERT #DirectoryTree (subdirectory, depth, isfile)
EXEC master.sys.xp_dirtree @BasePath, 1, 1;
-- SELECT subdirectory, * FROM #DirectoryTree
-- Start Cursor
DECLARE @fileName varchar(MAX) -- filename for backup
DECLARE fileList CURSOR FOR ( SELECT subdirectory FROM #DirectoryTree WHERE isfile = 1 )
OPEN fileList
FETCH NEXT FROM fileList INTO @fileName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @fileName = @BasePath + '\' + @fileName
PRINT @fileName
PRINT 'You can do something with the file here...'
-- SET @fileContents = 'blabla' get the file contents
--EXECUTE('fileContents')
FETCH NEXT FROM fileList INTO @fileName
END
CLOSE fileList
DEALLOCATE fileList
-- End Cursor
IF OBJECT_ID('tempdb..#DirectoryTree')IS NOT NULL
DROP TABLE #DirectoryTree;
答案 1 :(得分:1)
您可以使用sqlcmd
获取文件名并针对您的实例运行脚本。你可以这样做:
DECLARE @path VARCHAR(128) = 'C:\SQLScripts\ '
,@cmd VARCHAR(1024)
CREATE TABLE dirList (
line varchar(1000)
)
SET @cmd = 'dir /b ' + @path + '*.sql'
INSERT INTO dirList (line)
EXEC xp_cmdshell @cmd
DECLARE @actualFile VARCHAR(256)
DECLARE cur CURSOR FAST_FORWARD READ_ONLY FOR
SELECT * FROM dirList WHERE line IS NOT NULL;
OPEN cur
FETCH NEXT FROM cur INTO @actualFile
WHILE @@FETCH_STATUS = 0
BEGIN
SET @cmd = 'sqlcmd -S <ComputerName>\<InstanceName> -i ' + @path + @actualFile
EXEC xp_cmdshell @cmd
FETCH NEXT FROM cur INTO @actualFile
END
CLOSE cur
DEALLOCATE cur
DROP TABLE dirList
注意: