Try something like this. It is written to run against the NorthWind
database.
-------------------------------------------------------------------------------
CREATE PROCEDURE TestMe AS
SET NOCOUNT ON
DECLARE @comp_id INTEGER
DECLARE @emp_id INTEGER
DECLARE @terr_id INTEGER
DECLARE @curr_id INTEGER
DECLARE @terr VARCHAR(4096)
CREATE TABLE #stack
(
stack_nbr INTEGER IDENTITY NOT NULL PRIMARY KEY,
employee_id INTEGER NOT NULL,
territory_id INTEGER NULL,
)
CREATE TABLE #results
(
result_nbr INTEGER IDENTITY NOT NULL PRIMARY KEY,
employee_id INTEGER NOT NULL,
territory VARCHAR(4096),
)
INSERT INTO #stack
SELECT EmployeeID, TerritoryID
FROM EmployeeTerritories
ORDER BY EmployeeID, TerritoryID
SELECT @comp_id = 0
SELECT @terr = ''
-- process items in stack table
WHILE EXISTS(SELECT * FROM #stack)
BEGIN
SET ROWCOUNT 1 -- select the first item from the stack
SELECT @curr_id = stack_nbr, @emp_id = employee_id, @terr_id =
territory_id FROM #stack
IF @comp_id = 0
BEGIN
SELECT @terr = CAST(@terr_id AS VARCHAR(256))
SELECT @comp_id = @emp_id
END
ELSE
BEGIN
IF @comp_id = @emp_id
BEGIN
SELECT @terr = @terr + ', ' + CAST(@terr_id AS VARCHAR(256))
END
ELSE
BEGIN
INSERT INTO #results
VALUES (@comp_id, @terr)
SELECT @terr = CAST(@terr_id AS VARCHAR(256))
SELECT @comp_id = @emp_id
END
END
DELETE FROM #stack WHERE stack_nbr = @curr_id
END
INSERT INTO #results
VALUES (@comp_id, @terr)
SET ROWCOUNT 0
SELECT *
FROM #results
ORDER BY employee_id
DROP TABLE #stack
DROP TABLE #results
SET NOCOUNT OFF
------------------------------------------------------------------
- Hammer |