Click here to Skip to main content
16,021,209 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have a database table student(name,marks).
i want to select student names where marks is equal to or closest to x;
where x is the integer number entered by user in c# windows form

please help me i really need it

Tushar
Posted

something like:
SQL
select name from students where abs(mark-x)=(select min(abs(mark-x)) from students)
 
Share this answer
 
Comments
TusharZoo 3-Jul-14 9:29am    
hello sir thank you.. it is working ..i want to add something more in this query that if user enters < minimum marks then procedure will not return anything
 
Share this answer
 
Comments
TusharZoo 3-Jul-14 9:36am    
thank you ma'am .. :) :)
<pre lang="SQL">

YourTable 
studentName	Marks
Mark	        100
Tisa	        200
John	        250
Michelle	150
Parker	        450
Pete	        50
Ben	        400
Col	        325
Mis	        435
Aai	        265

First Create a Procedure Like this

CREATE PROCEDURE [dbo].[usp_FetchRecord] 
	@UserEnteredValue int
AS
BEGIN
	SET NOCOUNT ON;
	SELECT TOP 1 studentName,Marks FROM YourTable 
        WHERE Marks>=@UserEnteredValue order by Marks asc
END

-- To run the Procedure, here user has enetered 200
--EXEC [dbo].[usp_FetchRecord] 200

Result
studentName	Marks
Tisa	        200


Code Behind on Button Click :

C#
private void button1_Click(object sender, EventArgs e)
        {
            DataTable dttable = new DataTable();
            using (var con = new      SqlConnection(ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString))
            using (var cmd = new SqlCommand("usp_FetchRecord", con))
            using (var da = new SqlDataAdapter(cmd))
            {
                cmd.Parameters.AddWithValue("@UserEnteredValue", textBox1.Text);
                cmd.CommandType = CommandType.StoredProcedure;
                da.Fill(dttable);
            }
            // You can use this data table dttable to get the result and display it.
        }
 
Share this answer
 
Comments
TusharZoo 3-Jul-14 8:31am    
hello sir ..thank you for your answer but my problem is that i want the sql query for

--> when user entered 200 it gives Tisa
--> when user entered 201 it also gives Tisa because it is closest for 200 marks

please help me !!!
CHill60 3-Jul-14 8:31am    
If the user enters 101 your procedure will return Tisa on 200 instead of Mark on 100
TusharZoo 3-Jul-14 8:38am    
sir if user enters 101 procedure will return Mark because it is nearest to 100
CHill60 3-Jul-14 9:58am    
WHERE Marks>=@UserEnteredValue order by Marks asc will exclude Mark = 100 if 101 is entered
TusharZoo 3-Jul-14 10:11am    
ohk sir i will try ... thank you :)

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