我使用以下脚本截断数据库的日志文件。但是我必须在单独的窗口中执行以下脚本结果,因此我无法安排作业。
SET NOCOUNT ON
SELECT
'USE [' + d.name + N']' + CHAR(13) + CHAR(10)
+ 'DBCC SHRINKFILE (N''' + mf.name + N''' , 0, TRUNCATEONLY)'
+ CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10)
FROM
sys.master_files mf
JOIN sys.databases d
ON mf.database_id = d.database_id
WHERE d.database_id > 4 and mf.type_desc = 'LOG'
预期的O / P是必须运行脚本而不是复制粘贴上述查询结果
答案 0 :(得分:1)
SET NOCOUNT ON
DECLARE @LOG TABLE (
QUERY varchar(max)
)
DECLARE @QUERY varchar(max)
INSERT INTO @LOG
SELECT
'USE [' + d.name + N']' + CHAR(13) + CHAR(10)
+ 'DBCC SHRINKFILE (N''' + mf.name + N''' , 0, TRUNCATEONLY)'
+ CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10)
FROM sys.master_files mf
JOIN sys.databases d
ON mf.database_id = d.database_id
WHERE d.database_id > 4
AND mf.type_desc = 'LOG'
DECLARE C CURSOR FOR
SELECT
QUERY
FROM @LOG
OPEN C
FETCH NEXT FROM C INTO @QUERY
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @QUERY
EXEC (@QUERY)
FETCH NEXT FROM C INTO @QUERY
END
CLOSE C
DEALLOCATE C
答案 1 :(得分:1)
您可以使用Dynamic SQL实现此功能,而无需使用cursor
:
SET NOCOUNT ON
DECLARE @SQL VARCHAR(MAX) = ''
SELECT @SQL = @SQL +
'USE [' + d.name + N']' + CHAR(13) + CHAR(10)
+ 'DBCC SHRINKFILE (N''' + mf.name + N''' , 0, TRUNCATEONLY);'
+ CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10)
FROM
sys.master_files mf
JOIN sys.databases d
ON mf.database_id = d.database_id
WHERE d.database_id > 4 and mf.type_desc = 'LOG'
PRINT (@SQL)
EXEC (@SQL)
做同样的事情...