How to Delete top 1 item after using CTE (Common Table Expression)

King Java 770 Reputation points
2025-04-15T19:23:50.7666667+00:00

I am trying to delete top 1* item after using CTE.

I have the bottom T-SQL statement which works fine with select statement on the second part.

with cte as
(
    select *, 
           email_cnt = count(*) over (partition by "User"),
		   duplicate_Yes =	case when count(AccessToAllLocations) over (partition by "User") > 1
									and 
									count("Location") over (partition by "User") > 1
                                then 1
                                else 0
                                end
    from   [dbo].[tblPBIGroup_CA]
)
select top 1*  from cte c
where  email_cnt > 1
and    duplicate_Yes = 1
order by DateLoad asc

But, I am trying to delete not select.

How do I modify to make it work?

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,705 questions
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 58,701 Reputation points
    2025-04-15T20:04:13.21+00:00

    The CTE is running a query so you cannot delete from that. Use the Delete-Select syntax of SQL to delete from the table the results of running the query.

    ;WITH cte (...)
    DELETE FROM [tblPBIGroup_CA]
    FROM [tblPBIGroup_CA] t
    JOIN (SELECT TOP 1 * FROM cte...) c ON <key joining tblPBIGroup_CA to itself>
    
    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.