I have 2 SQL Server atabases A and B and want to copy a view from database A to database B using SQL only. B is used as history db, all the tables from A are also in B.
The existent views from A should be copied (re-created) into B in a way that they point to data in B.
The task is easy to solve using SQL Management Studio (e.g. here), but I need to be able to copy these views using my own program.
Where is the necessary information stored to generate the CREATE VIEW statements?
Could SELECT INTO or INSERT INTO provide a solution to my problem?
If you want to create all views, then:
If you want this to be repeatable, you need to also drop each view first, if it already exists in the destination database. So for example:
Now keep in mind that this will not create indexes if any of these are indexed views, it also doesn’t validate that the view can actually be created in the other database (unless you are positive that all the dependent objects are identical between the two databases), and doesn’t ensure the order of creation (in the case where ViewA calls ViewB, it may not create them in the correct order). Much better to use a schema comparison tool to automate this for you. I wrote about this here:
http://bertrandaaron.wordpress.com/2012/04/20/re-blog-the-cost-of-reinventing-the-wheel/