Assuming this is for SQL Server: CTE is only suitable for statement one - so you cannot have both SELECT and INSERT - just use INSERT :
WITH cOldest AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY [MyKey] ORDER BY SomeColumn DESC) AS rnDOB FROM MyTable ) INSERT INTO
This requires that #MyTempTable already exists. If you want to create it using SELECT , use this syntax:
WITH cOldest AS ( ..... ) SELECT c.* INTO
source share