Problem solve Get help with specific problems with your technologies, process and projects.

Retrieving the row for the Nth largest parametric column in a parametric table

This code returns the row corresponding to the Nth largest value for a given column name in a given table.

This piece of code returns the row corresponding to the Nth largest value for a given column name in a given table.

  
Create proc sp_find_value (@tablename varchar(50),
                           @column varchar(50),
                           @n int)
AS
declare @sqlStatment varchar(200)
set @sqlStatment  = 'select * from ' + @tableName + ' a ' + 
                   'where ' + convert (varchar(10),@n) + 
                   '=(select count(distinct ' + @column + ')' +
                   ' from  ' + @tableName + ' b ' +
                   ' where ' + 'a.'+ @column +  ' <= ' + 'b.' + @column + ')'
exec (@sqlStatment)
go

Here is out to use it:

exec sp_find_value 'products','unitprice',3

For More Information

  • What do you think about this tip? E-mail the editor at tdichiara@techtarget.com with your feedback.
  • The Best SQL Server Web Links: tips, tutorials, scripts, and more.
  • Have an SQL Server tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize--submit your tip today!
  • Ask your technical SQL Server questions--or help out your peers by answering them--in our live discussion forums.
  • Check out our Ask the Experts feature: Our SQL, Database Design, Oracle, SQL Server, DB2, metadata, and data warehousing gurus are waiting to answer your toughest questions.

Dig Deeper on SQL Server Database Modeling and Design

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.

-ADS BY GOOGLE

SearchBusinessAnalytics

SearchDataCenter

SearchDataManagement

SearchAWS

SearchOracle

SearchContentManagement

SearchWindowsServer

Close