Search code examples
sql-serversql-insertwith-statement

Why does this not work: INSERT SQL statement using "With ROW_NUMBER" . Error is Incorrect syntax near the keyword 'With'


I am using this syntax which works in components separately but when I use it all together, it stops to work I get a syntax error: Incorrect syntax near the keyword 'With'. I am not sure why.

if OBJECT_ID ('tempdb..#Assignments') is not null 
   drop table #Assignments
create table #Assignments
(
SerialNumber varchar(24) not null
)
insert into #Assignments (SerialNumber)
    With Row_Number as 
        (
        select SerialNumber,row_number() 
        over (partition by serialNumber order by serialnumber) as Row_Num
        from Monitor  
        where SerialNumber IS NOT NULL
        ) 
    select SerialNumber from Row_Number where Row_Num > 1

Solution

  • It's not valid syntax. When you use a CTE the WITH is the first part of the statement.

    if OBJECT_ID ('tempdb..#Assignments') is not null 
        drop table #Assignments;
    create table #Assignments
    (
        SerialNumber varchar(24) not null
    );
    
        With Row_Number as 
            (
                select SerialNumber,row_number() over (partition by serialNumber order by serialnumber) as Row_Num
                from Monitor  
                where SerialNumber IS NOT NULL
            ) 
        insert into #Assignments (SerialNumber)
        select SerialNumber from Row_Number where Row_Num > 1;
    

    Side note: make sure you include ; after your statements when you are using CTE's. The statement prior to WITH has to be terminated or you will get a syntax error.