Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2008 R2: 'CREATE/ALTER VIEW' does not allow specifying the database name as a prefix to the object name

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

like image 894
MAK Avatar asked Sep 28 '15 16:09

MAK


3 Answers

It is really simple: you need to change the database

USE DB2
GO

ALTER VIEW View1
    ...
like image 87
Code Different Avatar answered Oct 16 '22 07:10

Code Different


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

like image 25
Just Do It Avatar answered Oct 16 '22 05:10

Just Do It


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'))

like image 25
Eric Avatar answered Oct 16 '22 07:10

Eric