Sie sind auf Seite 1von 1

Script: Find the Median Value of a Column in a Table

The Procedure Uses Dynamic SQL along with a SCROLL cursor to find the median value in a
table. First a temporary table is created with a sql_variant column. The table is then filled with
all the selected column values sorted by value. Afterwards, an absolute fetch to the middle of
cursor is done in order To find the median value.

/*
Procedure To calculate the Median
By Eli Leiba
Date 08/07/2004
General : Procedure Uses Dynamic sql along with SCROLL cursor
- I create a temporary table with an SQL_VARIANT colunm
- I inserted all values of the given column TO that table
sorted by the column's value
- I fetched absolute to middle of cursor in order To
find the median value
*/
Create proc sp_calc_median
(@tablename varchar(50),
@columnname varchar(50),
@result sql_variant OUTPUT)
as
begin
declare @sqlstmt varchar(200)
declare @midCount int
set noCount on
set @sqlstmt = 'Insert #tempmedian select ' + @columnname +
' FROM ' + @tablename + ' order by 1 asc '
Create Table #tempmedian (col sql_variant)
exec (@sqlstmt)
declare c_med cursor SCROLL for select * from #tempmedian
select @midCount = round ( count(*) * 0.5,0 ) from #tempmedian
open c_med
fetch absolute @midCount from c_med into @result
close c_med
deallocate c_med
drop table #tempmedian
end
go
-- Examples How To Use the procedure
declare @res sql_variant -- declaring an sql_variant column
exec sp_calc_median 'northwind..products','productname',@res OUTPUT -- exec proc
print convert (nvarchar,@res) -- getting the result for a varch column
exec sp_calc_median 'northwind..products','UnitPrice',@res OUTPUT
print convert (real,@res) -- getting result for a numeric column