就个人而言,我会考虑编写存储过程。MSDN 文档很好,如果您快速搜索,在线上有很多资源。
或者你可以做这样的事情来让它发生(你需要有执行命令外壳等的权限):
CREATE TABLE ##SQLFiles ( SQLFileName VARCHAR(2000))
GO
INSERT INTO ##SQLFiles
EXECUTE master.dbo.xp_cmdshell 'dir /b "C:\SQL Scripts\*.sql"'
GO
DECLARE cFiles CURSOR LOCAL FOR
SELECT DISTINCT [SQLFileName]
FROM ##SQLFiles
WHERE [SQLFileName] IS NOT NULL AND
[SQLFileName] != 'NULL'
ORDER BY [SQLFileName]
DECLARE @vFileName VARCHAR(200)
DECLARE @vSQLStmt VARCHAR(4000)
OPEN cFiles
FETCH NEXT FROM cFiles INTO @vFileName
WHILE @@FETCH_STATUS = 0
BEGIN
-- The following SET command must be on a single line or else an error will be generated.
-- It is split in this script for readability purposes.
SET @vSQLStmt = 'master.dbo.xp_cmdshell ''osql -S Server Name -U User Name -P Password
-d Database Name -i "C:\SQL Scripts\' + @vFileName + '"'''
EXECUTE (@vSQLStmt)
FETCH NEXT FROM cFiles INTO @vFileName
END
CLOSE cFiles
DEALLOCATE cFiles
GO
DROP TABLE ##SQLFiles
GO