Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a indexed view with tables from 2 different databases using Schemabinding

Here's the conondrum...

I have 2 databases on the same SQL Server 2008 R2 instance.

DB-One is for the website and the DB-two is a datadumb that gets updated daily from a dump.

Now I want to create an indexed view on DB-One where I am referencing 2 tables from DB 2.

So my query is something like

SELECT 
    TBA.COLA, TBB.COlA
FROM 
    DB-ONE.TBA.COLA A
JOIN 
    DB-TWO.TBB.COLA B ON (A.Id= B.Id)

Now this query works fine, obviously... However if I try and create a view with the following syntax it gives me an error

CREATE VIEW TESTVIEW WITH SCHEMABINDING AS

Error:

Cannot schema bind view 'TESTVIEW' because name 'DB-ONE.TBA.COLA A' is invalid for schema binding. Names must be in two-part format and an object cannot reference itself.

So if this approach is not possible then can anybody suggest any alternatives?

like image 215
MarsOne Avatar asked Dec 05 '14 15:12

MarsOne


1 Answers

As mentioned in the error message, when using schema binding "Names must be in two-part format " which means they must be in [schema].[tablename] format, so the tables cannot be in 2 separate databases.

  • Option 1: have a scheduled ETL job that persists the view data in a table in Db-One, index that table as needed, and then schedule ETL to load after the daily "data dump".

Run this once

USE [DB-ONE]
GO
CREATE TABLE dbo.myReport(/*column structure of your indexed view goes here*/);
go
--index table as needed
go

Then schedule this to run from DB-ONE after the daily "data dump" is loaded into DB-TWO:

use [DB-ONE]
GO
insert into dbo.myReport(/*list of columns*/)
SELECT TBA.COLA, TBB.COlA
FROM DB-ONE.TBA.COLA A
JOIN DB-TWO.TBB.COLA B ON (A.Id= B.Id)
;
  • Option 2: you could copy over all the data from the DB-TWO table into DB-ONE and then still create your indexed view on the DB-ONE tables.
like image 107
BateTech Avatar answered Sep 22 '22 22:09

BateTech