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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With