Export All Views to Text Files

时光总嘲笑我的痴心妄想 提交于 2020-01-25 09:27:05

问题


There are a number of views in a database on one of our servers. I need to save all the view definitions as text files in the following format:

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

The text file should be named as Schema_Name.VIEW_NAME.txt

I don't want to do this manually as this would take up all my time. Any idea if this can be automated? Maybe using SSIS or something?


回答1:


You can get all views with this query:

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

just create cursor with this select, and for each row store data to file with something like this:

DECLARE @Cmd AS VARCHAR(MAX)
SET @Cmd ='echo ' +  @script + ' > C:\' + @schema + '.' + @view_name + '.txt'
EXECUTE Master.dbo.xp_CmdShell  @Cmd


来源:https://stackoverflow.com/questions/32881802/export-all-views-to-text-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!