Search code examples
sqlsql-serverstored-procedurespartition-by

saving to a temporary table while having an over partition command in mssql


I want to save my select statement to a temporary table but it is using a partition command, which is why I do not know how it would be saved.

This is my sample select statement:

;WITH A
AS
(
 SELECT ROW_NUMBER() OVER(PARTITION BY A.colRecordLocator, A.farerId,
    A.colOnOff , A.VendorID 
    ORDER BY A.TagID DESC) xRow, A.*   
 FROM dbo.TVehicle A
)SELECT A.* FROM A WHERE A.xRow = 1

I want to put it inside a temporary table #tempTable1. I need to do this because I am still going to use the values to be joined to another table. I am also doing this because I need to use the temporary table on other queries inside a stored procedure, and I do not want to modify everything again, just change the data (with the partition command) on the temporary table would be enough to update my stored procedure.

What should I do to allow me to save this to a temporary table?


Solution

  • ;WITH A
    AS
    (
     SELECT ROW_NUMBER() OVER(PARTITION BY A.colRecordLocator, A.farerId,
        A.colOnOff , A.VendorID 
        ORDER BY A.TagID DESC) xRow, A.*   
     FROM dbo.TVehicle A
    ) 
    SELECT A.* Into #TempTable  
    FROM A 
    WHERE 
    A.xRow = 1
    

    Here is a simple example: http://sqlfiddle.com/#!6/ccfdb4/1/0