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 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
Sign up to request clarification or add additional context in comments.

2 Comments

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 - Ah I often mess that up when I haven't got the data to test against! Done.
1
SELECT id
FROM table
WHERE sub_id = @target
UNION ALL
SELECT @target

1 Comment

@0dd_b1t: Seems that @Martin's answer is what you're looking for

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.