Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy view into another database

Tags:

sql

sql-server

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?

like image 457
a1337q Avatar asked Jul 20 '26 17:07

a1337q


1 Answers

USE DatabaseA;
GO

DECLARE @sql NVARCHAR(MAX);

SELECT @sql = definition
FROM sys.sql_modules
WHERE [object_id] = OBJECT_ID('dbo.ViewName');

EXEC DatabaseB..sp_executesql @sql;

If you want to create all views, then:

USE DatabaseA;
GO

DECLARE @sql NVARCHAR(MAX);

SET @sql = N'';

SELECT @sql = @sql + CHAR(13) + CHAR(10) + 'GO'
    + CHAR(13) + CHAR(10) + m.definition
FROM sys.sql_modules AS s
INNER JOIN sys.objects AS o
ON s.[object_id] = o.[object_id]
WHERE o.type_desc = 'VIEW';

EXEC DatabaseB..sp_executesql @sql;

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:

USE DatabaseA;
GO

DECLARE @sql NVARCHAR(MAX);

SET @sql = N'';

SELECT @sql = @sql + CHAR(13) + CHAR(10) + 'IF OBJECT_ID('''
    + QUOTENAME(SCHEMA_NAME(o.[schema_id]))
    + '.' + QUOTENAME(o.name) + ''') IS NOT NULL
      BEGIN
        DROP VIEW ' 
        + QUOTENAME(SCHEMA_NAME(o.[schema_id]))
        + '.' + QUOTENAME(o.name) + ';
      END'
    + CHAR(13) + CHAR(10) + 'GO'
    + CHAR(13) + CHAR(10) + s.definition
FROM sys.sql_modules AS s
INNER JOIN sys.objects AS o
ON s.[object_id] = o.[object_id]
WHERE o.type_desc = 'VIEW';

EXEC DatabaseB..sp_executesql @sql;

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/

like image 116
Aaron Bertrand Avatar answered Jul 22 '26 07:07

Aaron Bertrand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!