0

我们其中一台服务器上的数据库中有许多视图。我需要将所有视图定义保存为以下格式的文本文件:

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 之类的?

4

2 回答 2

5

您可以使用此查询获取所有视图:

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

只需使用此选择创建游标,并为每行存储数据以如下方式归档:

DECLARE @Cmd AS VARCHAR(MAX)
SET @Cmd ='echo ' +  @script + ' > C:\' + @schema + '.' + @view_name + '.txt'
EXECUTE Master.dbo.xp_CmdShell  @Cmd
于 2015-10-01T07:56:21.040 回答
0

可能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

在此处输入图像描述

于 2022-01-14T16:33:27.017 回答