I have to 2 databases DB1
and DB2
.
I have a view called View1
which is stored in the database DB2
. Now I want to ALTER VIEW
from DB1
database.
My attempt:
ALTER VIEW DB2..View1
AS
SELECT * FROM DB2..Test;
But I'm getting an error:
'CREATE/ALTER VIEW' does not allow specifying the database name as a prefix to the object name
It is really simple: you need to change the database
USE DB2
GO
ALTER VIEW View1
...
Comments are self explanatory. You need to be working in the DataBase your view is for/from. Switch your connection to DB2
and you should be able to CREATE
and ALTER
a/your view. From MSDN
In my case I'm trying to run a script to create/alter a view in different database, so I'm using EXEC (...)
to create my views..
But I hit a bit of a paradox:
EXEC ('CREATE VIEW...')
will not let you specify the database. You have to switch to that database to create the view.
But you can't do EXEC ('USE [db]; CREATE VIEW...')
as CREATE VIEW
will demand it be the first command.
I got around this problem feeling like I went Inception:
EXEC('USE [db]; EXEC('CREATE VIEW'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With