mardi 5 mai 2015

Using SQL Server, how to return a list from a While loop, and should I be using a While loop?

I have table A, with columns Id and ParentId. Given an Id, I want to return all ParentId.

Meaning, given an Id, I want to return all entries' ParentId, and then I want to check to see if the recorded ParentId is entered into the table as an Id, if so I want to find it's ParentId, etc...

For example, if I have the simple example of a table like:

Id | ParentID
---+---------
1    0    
2    1
3    2
4    3
5    4 
6    5
7    6

My query to print all the parents of Id=7 looks like this:

DECLARE @ParentId INT;

SET @ParentId = 7;

WHILE(@ParentId > 0)
BEGIN 
  SELECT @ParentId = ParentId
  FROM A
  WHERE Id = @ParentID

  PRINT @ParentId
END

This query prints all the ParentId. But, is there a way to return the IDs? In that, if I was calling this query from PHP I would want to get a list of the ParentIds, but my query doesn't actually return anything.

Additionally, I wonder if a while loop is the correct solution. Would a recursive query be faster? If so, any advice on how to convert this to a recursive query?

*Edit

I need to access the list of ParentIds from PHP. Now I'm trying to build a comma-delimited list of Ids to return from the query, which I can later parse in PHP. However, the below query gives me error:

A RETURN statement with a return value cannot be used in this context.

DECLARE @ParentId INT, @ParentList varchar(max);

    SET @ParentId = 7;

    WHILE(@ParentId > 0)
    BEGIN 
      SELECT @ParentId = ParentId
      FROM A
      WHERE Id = @ParentID

      SET @ParentList = @ParentList | CAST(@ParentId as varchar(20)) | ','; 
    END
    RETURN @ParentList;

What should I do to return a list? Additionally, how can I get the returned value when I execute this statement in PHP?

Aucun commentaire:

Enregistrer un commentaire