C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Communities   Interview   Jobs   Projects   Offshore Development    
Silverlight Tutorials | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Revenue Sharing |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...

New Feature: Community Sites: Create your own .NET community website and start earning from Google AdSense ! It's Free !




How to find out the nth highest number in a database column


Posted Date: 18 Jun 2007    Resource Type: Code Snippets    Category: ADO.NET

Posted By: Abhishek Arya       Member Level: Diamond
Rating:     Points: 10



You can use this stored procedure to find the nth highest number in a database column. For example, if you want to find the second largest number, pass 2 as the value for the parameter 'nth'.


CREATE PROC nth
(
@table_name sysname,
@column_name sysname,
@nth int
)
AS
BEGIN

--Purpose: To find out the nth highest number in a column. Eg: Second highest salary from the salaries table
--Input parameters: Table name, Column name, and the nth position


SET @table_name = RTRIM(@table_name)
SET @column_name = RTRIM(@column_name)

DECLARE @exec_str CHAR(400)
IF (SELECT OBJECT_ID(@table_name,'U')) IS NULL
BEGIN
RAISERROR('Invalid table name',18,1)
RETURN -1
END

IF NOT EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @table_name AND COLUMN_NAME = @column_name)
BEGIN
RAISERROR('Invalid column name',18,1)
RETURN -1
END

IF @nth <= 0
BEGIN
RAISERROR('nth highest number should be greater than Zero',18,1)
RETURN -1
END

SET @exec_str = 'SELECT MAX(' + @column_name + ') from ' + @table_name + ' WHERE ' + @column_name + ' NOT IN ( SELECT TOP ' + LTRIM(STR(@nth - 1)) + ' ' + @column_name + ' FROM ' + @table_name + ' ORDER BY ' + @column_name + ' DESC )'
EXEC (@exec_str)

END










Responses

Author: aditya kumar    17 May 2008Member Level: Bronze   Points : 2
immedaitely send my the details that how we will call this
procedure on c# page



Feedbacks      
Popular Tags   What are tags ?   Search Tags  
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Creation of Groups and using Group classes
Previous Resource: Addition, updation and searching employee details using grid
Return to Discussion Resource Index
Post New Resource
Category: ADO.NET


Post resources and earn money!
 
Related Resources



dotNet Slackers   BizTalk Adaptors    Web Design

conference calls

Contact Us    Privacy Policy    Terms Of Use