0

I want to create a View with a lenghty query like :

CREATE VIEW doubleV
AS 
SELECT * FROM X1 as R
WHERE [Ext] IN 
(
    SELECT [Ext] FROM X1 as RR
    WHERE RR.cliID=R.cliID 
    AND Soc='j'
    GROUP BY [Ext]  
    HAVING COUNT(*) > 1
)

But when i Select all elements from this VIEW, Sql server just execute the query inside the view, which takes much time.

Is it possible to execute the query at the VIEW CREATION ?

Does anything would allow me to make a temporary table with a query result ?

Fortune
  • 523
  • 1
  • 7
  • 21

2 Answers2

0

You can use

SELECT … INTO NewTableName
FROM …

to create a table with the results of a query (the table will lack any keys, and will be updatable).

You could also create an "Indexed View": which is a copy of the results of the view, generally intended to be updated from time to time (eg. an expensive query is run every few minutes to balance freshness of the results with cost of getting them). This is often called a "Materialised View".

Community
  • 1
  • 1
Richard
  • 106,783
  • 21
  • 203
  • 265
0

See here :

The result set of a standard view is not stored permanently in the database. Each time a query references the view, Microsoft® SQL Server™ 2000 dynamically merges the logic needed to build the view result set into the logic needed to build the complete query result set from the data in the base tables. The process of building the view results is called materializing the view.

So you need to create an INDEXED VIEW, in order to do this, you can read this.

The code you would need is the following (maybe some typos) :

CREATE VIEW doubleV
AS 
SELECT * FROM X1 as R
WHERE [Ext] IN 
(
    SELECT [Ext] FROM X1 as RR
    WHERE RR.cliID=R.cliID 
    AND Soc='j'
    GROUP BY [Ext]  
    HAVING COUNT(*) > 1
)
GO
CREATE UNIQUE CLUSTERED INDEX doubleVInd ON doubleV (field_you_want)

Where field_you_want is the field you index on, most probably an ID.

Pholochtairze
  • 1,836
  • 1
  • 14
  • 18