简体   繁体   English

遍历结果并为新数据库创建视图

[英]loop through results and create views for a new database

I am using SQL Server 2012. 我正在使用SQL Server 2012。

I am copying some view from one database to another one. 我正在将一些视图从一个数据库复制到另一个数据库。 I know I can use Task > Generate scripts to do this for me, however I would like to know how to do this in a different way. 我知道我可以使用“任务”>“生成脚本”为我执行此操作,但是我想知道如何以其他方式执行此操作。

If I run the query select * FROM INFORMATION_SCHEMA.VIEWS it will obviously return my a list of views in my current database. 如果我运行查询,选择* FROM INFORMATION_SCHEMA.VIEWS,显然它将返回我当前数据库中的视图列表。 In the view_definition column I can see it has the scripts to create the views. 在view_definition列中,我可以看到它具有创建视图的脚本。

Would I would like to know is how to loop through the results from (select * FROM INFORMATION_SCHEMA.VIEWS) and execute the scripts in the view_definition field? 我想知道如何遍历(选择* FROM INFORMATION_SCHEMA.VIEWS)的结果并执行view_definition字段中的脚本吗? I understand this may not be the best practise however I would just like to learn how you would do such a thing. 我了解这可能不是最佳做法,但是我只想了解您将如何做这样的事情。

You could try opening a cursor and creating the view for each row : 您可以尝试打开游标并为每一行创建视图:

USE [Target DB];
DECLARE @view VARCHAR(MAX)

DECLARE curs CURSOR 
FOR SELECT VIEW_DEFINITION FROM [Source DB].INFORMATION_SCHEMA.VIEWS

OPEN curs

FETCH NEXT FROM curs 
INTO @view
WHILE @@FETCH_STATUS = 0
BEGIN 
    EXEC(@view)
    FETCH NEXT FROM curs 
    INTO @view
END 
CLOSE curs
DEALLOCATE curs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM