2

Sorry for this maybe foolish question but i'm newbie to SQL Server. Here structure of my table of divisions at organization:

id int(16) -- simply unique id
sub_id int(16) -- this id of parent division in this table (if zero, than it don't have parent)
name VARCHAR(200) -- name of division

I need to create a simply procedure which return me all id of subdivisions in some division (with top division id too). I think i need array with subid's in loop, but i don't know how to create array in SQL Serve o_0 (omg.. array exist in (T)SQL language ? =). Help please. Or maybe another way to get it?

2
  • @abatishchev omg, you edited his question. kthxbye
    – alex
    Commented Oct 22, 2010 at 12:29
  • @alex: Do you think i shouldn't? Commented Oct 22, 2010 at 12:33

2 Answers 2

3

If I have understood your question correctly you need a recursive CTE.

CREATE PROCEDURE dbo.foo
@id int
AS

WITH divisions AS
(
SELECT id, sub_id, name
FROM YourTable
WHERE id = @id
UNION ALL
SELECT y.id, y.sub_id, y.name
FROM YourTable y
JOIN divisions d ON d.id = y.sub_id
)

SELECT id, sub_id, name
FROM divisions
2
  • you have a little mistake - "JOIN divisions d ON d.id = y.sub_id" change this and i will mark your answer as accepted =)
    – 0dd_b1t
    Commented Oct 22, 2010 at 13:08
  • @0dd_b1t - Ah I often mess that up when I haven't got the data to test against! Done. Commented Oct 22, 2010 at 13:10
1
SELECT id
FROM table
WHERE sub_id = @target
UNION ALL
SELECT @target
1
  • @0dd_b1t: Seems that @Martin's answer is what you're looking for Commented Oct 22, 2010 at 12:56

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.