Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL: Create a view that accesses multiple databases

I have a special case,

for example in table ta in database A, it stores all the products I buy

table ta( id, name, price ) 

in table tb in database B, it contain all the product that people can buy

table tb( id, name, price .... ) 

Can I create a view in database A to list all the products that I haven`t bought?

like image 212
jojo Avatar asked Jan 26 '10 22:01

jojo


People also ask

Can we create a view from multiple tables?

A view that combines data from multiple tables enables you to show relevant information in multiple tables together. You can create a view that combines data from two or more tables by naming more than one table in the FROM clause.

Can you query multiple databases in SQL?

Multiple Databases on One Server Instance For example, you can have a MySQL server installation on machine X that hosts both the customers and orders database. It is possible to use SQL to write one query that combines the information from many databases.

Can one instance have multiple databases?

It appears as though you cannot have multiple databases running under one instance. Without OPS or RAC, you must have one instance for each database if you want to access data in that database. However, it is possible to access another database's data through an instance by using Database Links.


2 Answers

Yes you can - the t-sql syntax is the same as within any other cross database call (within a stored procedure for example).

To reference your tables in the second database you simply need:

[DatabaseName].[Schema].[TableName]

So you would end up with something like

CREATE VIEW [dbo].[YourView] as select  a.ID,  a.SomeInfo,  b.SomeOtherInfo from TableInA a join DatabaseB.dbo.TableInB b on -- your join logic goes here 

Note that this will only work on the same server - if your databases are on different servers them you will need to create a linked server.

like image 177
David Hall Avatar answered Oct 01 '22 07:10

David Hall


As the other answers indicate, you can use the {LINKED_SERVER.}DATABASE.SCHEMA.OBJECT notation.

You should also be aware that cross-database ownership chaining is disabled by default.

So within a database, granting SELECT on a view allows a user who may not have SELECT on the underlying tables to still SELECT from the view. This may not work across to another database where the user does not have permissions on the underlying table.

like image 27
Cade Roux Avatar answered Oct 01 '22 08:10

Cade Roux