views:

73

answers:

4

Hi folks,

If i create an Indexed View (in Sql Server 2008), does this mean i copy all required the data from the source tables into a separate new table? Or are only some tiny pointers/indexes saved, to represent this view?

+2  A: 

When a unique clustered index is created on a view, the result set is stored in the database just like a table with a clustered index is stored.

As modifications are made to the data in the base tables, the data modifications are reflected in the data stored in the indexed view

~ from msdn

Anil
So the answer is ... 'Yes -the data is duplicated' ... ??
Pure.Krome
Yes -the data is duplicated.
Lieven
+2  A: 

Yes, the data is copied. Other database platforms such as Oracle refer to this as a Materialized View because the data will materialize into a physical form.

Joe Stefanelli
+2  A: 

Yes, the data is copied and stored separately, so if you modify the underlying table, your indexed view will update automatically. This causes a lot of lock contention. Also the indexed view may grow larger than the underlying tables and become counterproductive.

AlexKuznetsov
+1  A: 

You can use the (undocumented but widely used) DBCC PAGE command to see exactly what is stored. The following will create an indexed view and print the contents of the first data page.

SET NOCOUNT ON
IF OBJECT_ID('tempdb..#dbcc_ind') IS NOT NULL
    TRUNCATE TABLE #dbcc_ind
ELSE
    CREATE TABLE #dbcc_ind
    (PageFID  TINYINT, 
    PagePID INT,   
    IAMFID   TINYINT, 
    IAMPID  INT, 
    ObjectID  INT,
    IndexID  TINYINT,
    PartitionNumber TINYINT,
    PartitionID BIGINT,
    iam_chain_type  VARCHAR(30),    
    PageType  TINYINT, 
    IndexLevel  TINYINT,
    NextPageFID  TINYINT,
    NextPagePID  INT,
    PrevPageFID  TINYINT,
    PrevPagePID INT, 
    PRIMARY KEY (PageFID, PagePID));

IF OBJECT_ID('dbo.vtest') IS NULL
CREATE TABLE dbo.vtest (
i INT IDENTITY(1,1)  NOT NULL PRIMARY KEY,
c1 CHAR(500) NOT NULL DEFAULT REPLICATE('x',500), 
c2 CHAR(500) NOT NULL DEFAULT REPLICATE('y',500) 
)
GO

INSERT INTO dbo.vtest DEFAULT VALUES
GO 10

IF OBJECT_ID('dbo.ixViewTest') IS NULL
BEGIN
EXEC('CREATE VIEW dbo.ixViewTest
WITH SCHEMABINDING
AS
SELECT i,c1,c2
FROM dbo.vtest;')
EXEC('CREATE UNIQUE CLUSTERED INDEX [cix] ON [dbo].[ixViewTest] ([i] ASC)')
END
GO


DECLARE @command VARCHAR(1000)
SET @command = 'DBCC IND(' + QUOTENAME(DB_NAME()) + ', ixViewTest,1) WITH NO_INFOMSGS;'

INSERT INTO #dbcc_ind
    EXEC ( @command );


SELECT @command= 'DBCC PAGE (' + QUOTENAME(DB_NAME()) + ',' + CAST(PageFID AS VARCHAR(5)) + ',' + CAST(PagePID AS VARCHAR(10)) + ',1) ;'
FROM #dbcc_ind
WHERE PageType=1
 AND PrevPagePID=0


DBCC TRACEON(3604)
EXEC ( @command )
DBCC TRACEOFF(3604)
Martin Smith