ONYX
ONYX

Reputation: 5859

SQL cte delete operation

I have a cte that loops through the records creates a list and I pass a parameter of @ParamterID in a select statement but the set operations says incorrect syntax near Set and in that select it gets the path where I can do a search for the paths that are LIKE '%' + @Path + '%' and those are the items I want to delete from the table called Post. could someone help me complete this please and correct my SET @Path syntax

DELCARE @ParmeterID int = 3
DECLARE @Path nvarchar(MAX) 

WITH cte(Url, Level, Path, PostID, ParentPostID)
AS (

SELECT REPLACE(LOWER(Title), ' ', '-'), 1 AS Level, CAST(PostID as nvarchar(MAX)) as Path,
PostID, ParentPostID
FROM Post
WHERE ParentPostID IS NULL

UNION ALL

SELECT cte.Url, cte.Level + 1,
LOWER(cte.Path + '-' +  CAST(P.PostID AS VARCHAR(MAX))),
P.PostID,  P.ParentPostID 
FROM Post P 
INNER JOIN cte ON P.ParentPostID = cte.PostID
)
-- says incorrect sybnatx near Set @Path
SET @Path = (SELECT Path FROM cte WHERE PostID = @ParemeterID); 


-- list i want to delete --
SELECT * FROM cte WHERE Path LIKE '%' + @Path + '%'

delete -- list -- FROM Post --

Upvotes: 0

Views: 1052

Answers (1)

Michał Powaga
Michał Powaga

Reputation: 23183

I'm not sure what exactly you are trying to do (I don't know your table schema) but you can try this:

DECLARE @ParmeterID int = 3

WITH cte(Url, Level, Path, PostID, ParentPostID)
AS (
    SELECT REPLACE(LOWER(Title), ' ', '-'), 1 AS Level, CAST(PostID as nvarchar(MAX)) as Path,
    PostID, ParentPostID
    FROM Post
    WHERE ParentPostID IS NULL

    UNION ALL

    SELECT cte.Url, cte.Level + 1,
    LOWER(cte.Path + '-' +  CAST(P.PostID AS VARCHAR(MAX))),
    P.PostID,  P.ParentPostID 
    FROM Post P 
    INNER JOIN cte ON P.ParentPostID = cte.PostID
)

delete p
from post p
join cte on p.postId = cte.postId and 
    cte.path like '%' + (select top 1 [path] from cte where postId = @ParmeterID) + '%'

Addedd: Ordering by path, please mind that this is a quick and dirty way.

WITH cte(Url, Level, Path, PostID, ParentPostID, Sequence)
AS (
    SELECT REPLACE(LOWER(Title), ' ', '-'), 1 AS Level, CAST(PostID as nvarchar(MAX)) as Path,
    PostID, ParentPostID, right(replicate('0', 8) + cast(PostID as varchar(max)), 8)
    FROM Post
    WHERE ParentPostID IS NULL

    UNION ALL

    SELECT cte.Url, cte.Level + 1,
    LOWER(cte.Path + '-' +  CAST(P.PostID AS VARCHAR(MAX))),
    P.PostID,  P.ParentPostID, cte.sequence + right(replicate('0', 8) + cast(p.PostID as varchar(max)), 8)
    FROM Post P 
    INNER JOIN cte ON P.ParentPostID = cte.PostID
)
select Url, Level, Path, PostID, ParentPostID
from cte
order by Sequence

Upvotes: 2

Related Questions