Bkr Baroudi
Bkr Baroudi

Reputation: 39

Insert records into SQL Server 2012 Using C#

I am trying to insert records into SQL Server 2012 using C#.

I've done it in this way, but the problem is the insert record statement does not add the record at the end of the table.

It was working correctly, but sometimes (each time is different) it is inserting in the middle of the records and sometimes work correctly. it is not clear for me why this is happening.Figure

Any soultion ?

public partial class AddDoc : System.Web.UI.Page
{

SqlConnection con = new SqlConnection(@"Data Source=.\BAKRSQL; Database=Diseases Prediction Sys;Integrated Security=True");

protected void Page_Load(object sender, EventArgs e)
{
    SqlCommand cmd;
    string com = "select top 1 DId From Doctor ORDER BY DId Desc;";
    con.Open();
    cmd = new SqlCommand(com, con);
    object count = cmd.ExecuteScalar();
    if (count != null)
    {
        int i = Convert.ToInt32(count);
        i++;
        TextBox1.Text = i.ToString();
    }
    else
    {
        TextBox1.Text = "101";
    }
    con.Close();
}

protected void Button2_Click(object sender, EventArgs) 
{    SqlConnection con = new SqlConnection();
        con.ConnectionString =@"Data Source=.\BAKRSQL; Database=Diseases Prediction Sys;Integrated Security=True";
        con.Open();
        SqlCommand cmd = new SqlCommand("insert into Doctor(DId,Name,Address,Mobile) values (@DId,@Name,@Address,@Mobile);", con);
        cmd.Parameters.AddWithValue("@DId", TextBox1.Text);
        cmd.Parameters.AddWithValue("@Name", TextBox2.Text);
        cmd.Parameters.AddWithValue("@Address", TextBox3.Text);
        cmd.Parameters.AddWithValue("@Mobile", TextBox4.Text);
        cmd.ExecuteReader();
        con.Close();
        con.Open();
}
}

Upvotes: 1

Views: 63

Answers (3)

code4life
code4life

Reputation: 15794

If you want a physically ordered table, you need to create a clustered index on the field that you want the ordering to go by. You need to do this on the SQL server side - nothing to do with your C# code.

Upvotes: 0

Shubham Pandey
Shubham Pandey

Reputation: 1019

SQL Server maintains a relational model (i.e. based on the set theory). Therefore as is, there is no addition at the end of the table as such. While displaying records you may get a certain order, which can be changed using Order or Rank functions, as desired.

Upvotes: 0

TomTom
TomTom

Reputation: 62159

Tables have no order. Simple. You insert with ID - but that is just a field.

You want order, you select with order statement.

Fundamental in every SQL Databsae ever written.

Upvotes: 3

Related Questions