I have a ‘Categories’ table. Each row has a ‘CategoryId’ (required), and a ‘ParentCategoryId’ (not required). This allows for a Parent–>Child relationships between categories.
What I’m trying to do is select all categories, but if a parent–>child relationship exists, select only the parent.
Here’s what I’m currently trying, but it’s taking forever, and is just flat wrong. Disclaimer, SQL is NOT my strong suit!
declare @ProjectId int
set @ProjectId = 1
declare @catid int
declare @catname nvarchar(100)
declare @catprojid int
declare @catparentid int
declare @sortorder int
declare db_cursor cursor for
select categoryid,categoryname,projectid,parentcategoryid,sortorder from dbo.ProjectCategories
where ProjectId = @ProjectId
open db_cursor
fetch NEXT from db_cursor into @catid,@catname,@catprojid,@catparentid,@sortorder
while @@FETCH_STATUS = 0
begin
if @catparentid != null select * from dbo.ProjectCategories where CategoryId = @catparentid
else select @catid,@catname,@catprojid,@catparentid,@sortorder
end
close db_cursor
deallocate db_cursor
go
The following select retrieves all the Categories that are parents to at least one other Category: