为什么这不起作用:使用 "With ROW_NUMBER" 插入 SQL 语句。错误是关键字 'With' 附近的语法不正确

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

我正在使用这种在组件中单独工作的语法,但是当我一起使用它时,它停止工作我收到语法错误:关键字 'With' 附近的语法不正确。我不知道为什么。

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

这是无效的语法。当您使用 CTE 时,WITH 是语句的第一部分。

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;

旁注:确保在使用 CTE 时在语句后包含 ;WITH 之前的语句必须终止,否则会出现语法错误。