Click here to Skip to main content
15,879,239 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I've a table
SQL
create table marks(stdName nvarchar(30), marks float)

SQL
insert into marks
select 'std1', 98
union all select 'std2', 96
union all select 'std3', 95
union all select 'std4', 97
union all select 'std5', 93


I want to create stored procedure to select the row with 'th' highest marks as given input parameter.suppose if the input parameter is 3, it should display 'std2', 96 or if input parameter is 5, it should display 'std5', 93.
Posted

The procedure itself is quite straightforward, modify the statement as per requirements and then include inside a procedure, see CREATE PROCEDURE [^]

About the query, I would advice to separate the first column to two separate columns if the data describes different things. Concatenated columns should never be stored inside the database.

If the columns would be separate, then your query to fetch the row could be something like:
SQL
INSERT INTO Marks (strName, anotherfield, marks)
SELECT stdName, anotherField, marks
FROM  (
             select 'std' as stdName, 1 as AnotherField, 98 AS Marks
   union all select 'std' as stdName, 2 as AnotherField, 96 AS Marks
   union all select 'std' as stdName, 3 as AnotherField, 95 AS Marks
   union all select 'std' as stdName, 4 as AnotherField, 97 AS Marks
   union all select 'std' as stdName, 5 as AnotherField, 93 AS Marks) AS sub
WHERE sub.AnotherField = @procedureParameter
 
Share this answer
 
Comments
VJ Reddy 18-May-12 1:42am    
Nice answer. 5!
Wendelius 18-May-12 1:47am    
Thanks
nischalinn 18-May-12 1:43am    
what if there are so many rows??
Wendelius 18-May-12 1:47am    
Then the example insert would insert all the rows. If you want to get only one row, have a look at GROUP BY and HAVING: http://msdn.microsoft.com/en-us/library/ms177673.aspx[^]
If the requirement is to retrieve nth row from the Table then, the ROW_NUMBER function of Sql Server can be used for this purpose as shown below
SQL
CREATE PROCEDURE GetnthRow
    @nthRow nvarchar(30)
AS
WITH OrderedMarks AS
(
    SELECT ROW_NUMBER() OVER (ORDER BY stdName) as RowNo, stdName, marks
    FROM marks
)
SELECT stdName, marks
FROM OrderedMarks
WHERE RowNo=@nthRow
GO
 
Share this answer
 
v2
Comments
Wendelius 18-May-12 1:47am    
Good example!
VJ Reddy 18-May-12 1:54am    
Thank you, Mika :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900