The following procedure gets a tablename, column and integer (N) as parameters and finds the Nth largest value of a column in a specific table. For example, running it with "products," "UnitPrice," and "13," retrieves the 13th largest value of the UnitPrice column from the products table. If no such N exists, an error message is printed. The procedure code and usage is listed below:
create proc max_nth_value (@tablename varchar(50), @column varchar(50), @n int, @res decimal (10,4) OUTPUT) AS set nocount on declare @sqlStatment varchar(200) set @sqlStatment = 'select a.' + @column + ' from ' + @tableName + ' a ' + 'where ' + convert (varchar(10),@n) + '=(select count(distinct ' + @column + ')' + ' from ' + @tableName + ' b ' + ' where ' + 'a.'+ @column + ' <= ' + 'b.' + @column + ')' create table #tres (x decimal (10,4)) insert into #tres exec (@sqlStatment) if @@rowcount = 0 print 'No value found!' else select @res = x from #tres set nocount off go
Here is how to use it:
declare @res decimal (10,4) exec max_nth_value 'products','unitprice',8,@res OUTPUT print @res
About the authorEli Leiba works at the Israel Electric Company as a senior application DBA in Oracle and Microsoft SQL Server. He has certifications from Microsoft and BrainBench in Oracle and SQL Server database administration and implementation. Mr. Leiba holds a B.S. in computer science and has 11 years of experience working in the database field. Additionally, Mr. Leiba teaches SQL Server DBA and development courses at the Microsoft CTEC and also serves as a senior database consultant for several Israeli start-up companies.
For More Information
- Feedback: E-mail the editor with your thoughts about this tip.
- More tips: Hundreds of free SQL Server tips and scripts.
- Tip contest: Have a SQL Server tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize -- submit your tip today!
- Ask the Experts: Our SQL, database design, Oracle, SQL Server, DB2, metadata, and data warehousing gurus are waiting to answer your toughest questions.
- Forums: Ask your technical SQL Server questions--or help out your peers by answering them--in our active forums.
- Best Web Links: SQL Server tips, tutorials, and scripts from around the Web.