Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return IDENT_CURRENT which was inserted

I have INSERT INTO SqlCommand and I need to display after INSERT INTO the IDENT_CURRENT which was inserted with these values

SqlCommand sc = new SqlCommand("INSERT INTO kliplat (datum,text,castka,akce,subkey,priznak,rocnik) values (@datum,@text,@castka,@akce,@subkey,@priznak,@rocnik)", spojeni);
         spojeni.Open();

         sc.Parameters.AddWithValue("@subkey", vyber_id_kli);
         sc.Parameters.AddWithValue("@akce", vyberakce);
         sc.Parameters.AddWithValue("@priznak", vyberplat);
         sc.Parameters.AddWithValue("@datum", maskedTextBox1.Text);
         sc.Parameters.AddWithValue("@text", textBox1.Text);
         sc.Parameters.AddWithValue("@castka", textBox2.Text);
         sc.Parameters.AddWithValue("@rocnik", rocnik);

         sc.ExecuteReader();
         spojeni.Close();

This IDENT_CURRENT is: INTEGER IDENTITY PRIMARY KEY

Now I was dealing with this issue like this:

SqlCommand comm = new SqlCommand("SELECT IDENT_CURRENT ('mytable')", conn);
                 spojeni.Open();
                 int max = Convert.ToInt32(comm.ExecuteScalar());

                 spojeni.Close();

But I found out that this is extremely hazardous to do.

Thank you all for your time reading this.

like image 774
Marek Avatar asked Dec 16 '22 07:12

Marek


1 Answers

You could use a command that returns the newly inserted id:

SqlCommand sc = new SqlCommand(@"
    INSERT INTO kliplat (datum,text,castka,akce,subkey,priznak,rocnik) 
    VALUES (@datum,@text,@castka,@akce,@subkey,@priznak,@rocnik);
    SELECT scope_identity();
    ", spojeni);
...
var newIdentity = (long) sc.ExecuteScalar();
like image 50
Andomar Avatar answered Dec 18 '22 12:12

Andomar