Search code examples
sqlsql-serverdatabasecursor

Cursor with where null or value


I have a cursor or two rather because I can't figure out how to do this any other way.
The problem is that parentid can be null in the database. So I am testing if @parentid is not null then if it is I'm running one cursor where parentid = @parentid and then I have another one where parent id is null. (below)

declare findParent_c cursor for
        select ID , page
        from   dPageHierarchy
        where  profileid =  @profileId
        and parentid is null;
open findParent_c;
fetch findParent_c into @FindParentId, @ElementCheck;
while @@FETCH_STATUS = 0
begin

     -- Do stuff here.  

fetch findParent_c into @FindParentId, @ElementCheck;
end
close findParent_c;
deallocate findParent_c;

Does anyone have a way around this? I hate having double the code in the script.


Solution

  • Are you looking for this?

    declare findParent_c cursor for
    select ID , page
    from   dPageHierarchy
    where  profileid =  @profileId
    and ( (parentid = @parentid) or (parentid is null and @parentid is null) );