SELECT Query可以与SELECTS的子查询一起正常工作,但是当DELETE应用于同一子查询时,它将无法正常工作

时间:2018-09-29 00:42:18

标签: sql-server

假定Employee(Empid,name,salary)存在于SQL Server 2017表中,且记录重复且带有Empid,name,salary。

IF OBJECT_ID('TempDB..#Employee') IS NOT NULL 
    DROP TABLE #Employee

CREATE TABLE #Employee 
(
     Empid INT, 
     name VARCHAR(250), 
     salary FLOAT
)

INSERT INTO #Employee 
VALUES  (1008, 'Biju Joseph', 8500),
        (1008, 'Biju Joseph', 8500),
        (1008, 'Haris', 9000),
        (1009, 'John', 9500),
        (1009, 'John', 9500),
        (1010, 'SMITH', 10500)  

此嵌套查询对SELECT(对于SQL Server 2017)正常工作:

SELECT * 
FROM 
    (SELECT 
         name,
         ROW_NUMBER() OVER (PARTITION BY name, salary ORDER BY name) cnt 
     FROM  
         employee) mytable 
WHERE 
    cnt > 1

但是,当尝试删除时,它显示一条错误消息:

(DELETE FROM <tablename> WHERE <expression>)

DELETE FROM 
    (SELECT 
         name,
         ROW_NUMBER() OVER(PARTITION BY name, salary ORDER BY name) cnt 
     FROM 
         employee) mytable 
WHERE cnt > 1

错误:

  

第15级州立1行18的消息102
  '('附近的语法不正确。

     

第15级州立1行20的消息102
  “ mytable”附近的语法不正确

请注意:使用CTE或其他子查询时,我可以DELETE,但是在尝试DELETE时在此特定子查询中缺少什么?

2 个答案:

答案 0 :(得分:2)

您可以通过使用通用表表达式(CTE)来实现。

请尝试以下代码:

;WITH Duplicate (Name, Counts) AS
(
    SELECT 
        name, 
        ROW_NUMBER() OVER (PARTITION BY name, salary ORDER BY name) 
    FROM 
        #Employee
)
DELETE FROM Duplicate  
WHERE Counts > 1

答案 1 :(得分:1)

尝试

   DELETE C
   FROM 
           (SELECT name,row_number() OVER
              (PARTITION BY name,salary
               ORDER BY name)cnt FROM employee                 
           ) C 
           where C.cnt>1

我建议使用CTE