简体   繁体   中英

Creating View Using Synonyms in a Database Project (Visual Studio 2012)


I am hitting my head against the wall for a weird error I am getting in VS2012. I have a database project which includes some Synonyms. They are basically table references to another database in order to avoid dynamic SQL generation. I already added the required reference database for the Synonyms. Everything works great except a couple of views that are using some of those Synonyms! Since I am using the same Synonyms in my stored procedures and they are not causing any build failure, I am not sure why the views are causing problem.
The error message says: "SQL05313: Synonym 'xxx' refers to an invalid object.' Here is a sample code -
dbo.MyTable.sql...
CREATE SYNONYM [dbo].[MyTable] FOR [$(FOO_DB)].[dbo].[MyTable];
dbo.MyProc
CREATE [dbo].[MyProc] AS SELECT col1, col2, col3 FROM [dbo].[MyTable];
SUCCESS: this works
dbo.MyView.sql...
CREATE VIEW [dbo].[MyView] AS SELECT col1, col2, col3 FROM [dbo].[MyTable];
ERROR: SQL05313 Synonym '[dbo].[MyTable]' refers to an invalid object.


Has anyone else faced this issue? If yes, I appreciate your assistance :)

For some reason, reference errors in SPs are treated as warnings, while the same in views is treated as an error. Thus the error just means that the reference to $(FOO_DB) is not working - double check that the variable reference is set up correctly.

If you are referencing another DB project, it must be compilable to .dacpac individually (eg you cannot create circular references). If you really need circular reference (view in FOO_DB1 references FOO_DB2, and view in FOO_DB2 references FOO_DB1), look into composite objects (database reference of type same database).

I got this error, and I eventually found that I had run CREATE SYNONYM fred FOR ... instead of CREATE SYNONYM **dbo**.fred FOR ... It therefore created the synonym in my personal schema, instead of dbo , and this stopped the CREATE VIEW . I know that your code includes [dbo].[MyTable] , but do you have an identical synonym in your own schema, from a previous CREATE SYNONYM command that did not include the [dbo] , which might be confusing the CREATE VIEW command?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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