TSQL: Create a view that accesses multiple databases

后端 未结 3 2030
孤城傲影
孤城傲影 2020-12-01 07:36

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
)
         


        
3条回答
  •  感动是毒
    2020-12-01 08:06

    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.

提交回复
热议问题