将所有视图导出到文本文件
Export All Views to Text Files
我们的一台服务器上的数据库中有许多视图。我需要将所有视图定义保存为以下格式的文本文件:
IF OBJECT_ID('<[Schema_Name].[VIEW_NAME]>') IS NOT NULL
DROP VIEW <[Schema_Name].[VIEW_NAME]>
GO
<<View Definition Here>>
GO
GRANT SELECT ON <[Schema_Name].[VIEW_NAME]> TO [PUBLIC]
GO
文本文件应命名为Schema_Name.VIEW_NAME.txt
我不想手动执行此操作,因为这会占用我所有的时间。知道这是否可以自动化吗?也许使用 SSIS 之类的?
您可以使用此查询获取所有视图:
SELECT
s.name,
av.name,
sm.definition,
'IF OBJECT_ID('''+s.name+'.'+av.name+''') IS NOT NULL
DROP VIEW '+s.name+'.'+av.name+'
GO
'+sm.definition+'
GO
GRANT SELECT ON '+s.name+'.'+av.name+' TO [PUBLIC]
GO' AS script
FROM sys.views AS av
INNER JOIN sys.sql_modules AS sm
ON av.object_id = sm.object_id
INNER JOIN sys.schemas AS s
ON av.schema_id = s.schema_id
只需使用此 select 创建游标,并为每一行存储数据以这样的方式归档:
DECLARE @Cmd AS VARCHAR(MAX)
SET @Cmd ='echo ' + @script + ' > C:\' + @schema + '.' + @view_name + '.txt'
EXECUTE Master.dbo.xp_CmdShell @Cmd
可以information_schema
成为你的朋友:
SELECT v.TABLE_SCHEMA AS View_Schema
,v.table_name AS View_Name
,v.VIEW_DEFINITION AS Create_View_Script
FROM information_schema.VIEWS v
JOIN information_schema.columns c ON v.table_schema = c.table_schema
AND v.table_name = c.table_name
GROUP BY v.TABLE_SCHEMA
,v.table_name
,v.VIEW_DEFINITION
我们的一台服务器上的数据库中有许多视图。我需要将所有视图定义保存为以下格式的文本文件:
IF OBJECT_ID('<[Schema_Name].[VIEW_NAME]>') IS NOT NULL
DROP VIEW <[Schema_Name].[VIEW_NAME]>
GO
<<View Definition Here>>
GO
GRANT SELECT ON <[Schema_Name].[VIEW_NAME]> TO [PUBLIC]
GO
文本文件应命名为Schema_Name.VIEW_NAME.txt
我不想手动执行此操作,因为这会占用我所有的时间。知道这是否可以自动化吗?也许使用 SSIS 之类的?
您可以使用此查询获取所有视图:
SELECT
s.name,
av.name,
sm.definition,
'IF OBJECT_ID('''+s.name+'.'+av.name+''') IS NOT NULL
DROP VIEW '+s.name+'.'+av.name+'
GO
'+sm.definition+'
GO
GRANT SELECT ON '+s.name+'.'+av.name+' TO [PUBLIC]
GO' AS script
FROM sys.views AS av
INNER JOIN sys.sql_modules AS sm
ON av.object_id = sm.object_id
INNER JOIN sys.schemas AS s
ON av.schema_id = s.schema_id
只需使用此 select 创建游标,并为每一行存储数据以这样的方式归档:
DECLARE @Cmd AS VARCHAR(MAX)
SET @Cmd ='echo ' + @script + ' > C:\' + @schema + '.' + @view_name + '.txt'
EXECUTE Master.dbo.xp_CmdShell @Cmd
可以information_schema
成为你的朋友:
SELECT v.TABLE_SCHEMA AS View_Schema
,v.table_name AS View_Name
,v.VIEW_DEFINITION AS Create_View_Script
FROM information_schema.VIEWS v
JOIN information_schema.columns c ON v.table_schema = c.table_schema
AND v.table_name = c.table_name
GROUP BY v.TABLE_SCHEMA
,v.table_name
,v.VIEW_DEFINITION