Select SqlCommand return char

I have this piece of code that does a SELECT SqlCommand for column char(20) , but the result always returns 0 - this is because I donโ€™t know how to improve the code so that it returns char (20) - the value that is inserted into this column.

  SqlCommand sc = new SqlCommand("SELECT doklad FROM netpokl WHERE id_dok=" + newIdentity, spojeni); spojeni.Open(); int id_dok = Convert.ToChar(sc.ExecuteScalar()); spojeni.Close(); MessageBox.Show("" + id_dok); SqlCommand sc2 = new SqlCommand("UPDATE kliplat set doklad=@doklad WHERE id="+newIdentity, spojeni); sc2.Parameters.AddWithValue("@doklad", id_dok); spojeni.Open(); sc2.ExecuteNonQuery(); spojeni.Close(); 

Has anyone helped me improve my code?

+4
source share
1 answer
 SqlCommand sc = new SqlCommand(string.Format("SELECT doklad FROM netpokl WHERE id_dok='{0}'", newIdentity), spojeni); object obj = sc.ExecuteScalar(); if(obj == null) ; //Should show some message or throw exception string id_dok = obj.ToString().PadRight(20); //... SqlCommand sc2 = new SqlCommand(string.Format("UPDATE kliplat set doklad=@doklad WHERE id='{0}'",newIdentity), spojeni); //... 

By the way: I do not think it is necessary. In fact, you should check if the length is> 20, then the line should be truncated. You should also use nvarchar(20) in the database table.

+4
source

Source: https://habr.com/ru/post/1497506/


All Articles