Sunday, 17 September 2006

Custom aggregation in SQL Server with cursor (1)

If we have a Customer and a Order table, with one to many relationship, often we need to concatenate details records into master table for displaying. The details could be separated by semi colon into master table. The following is the Function required to get the concatenated value:

CREATE FUNCTION dbo.GetConcatenatedOrderNumbers
(
@CustomerID int
)
RETURNS nvarchar(500)
AS
BEGIN

declare @item nvarchar(200)
declare @result nvarchar(400)

select @item = ''
select @result = ''

declare item_cursor cursor for
select OrderNumber from Order Order.CustomerID=@CustomerID

Open item_cursor
Fetch next from item_cursor into @item

while @@FETCH_STATUS = 0
begin
select @result = @result + @item + '; '
Fetch next from item_cursor into @item
end

CLOSE item_cursor
DEALLOCATE item_cursor

-- remove space in the end
select @result = rtrim(@result)
-- remove the ; at the end
if(Len(@result) > 1)
begin
set @result = substring(@result, 1, len(@result) - 1)
end

RETURN @result
END

No comments: