简体   繁体   中英

How can I save a column value to a variable in SQL C#?

I am using windows forms C# and SQL. I have a table consists of two column:

Column1 = myID (primary key and unique ID)

Column2 = DateTime.

The following code inserts date/Time into the table:

 private void button1_Click(object sender, EventArgs e)
    {

 SqlConnection cn = new SqlConnection("Data Source=PCN-TOSH;Initial Catalog=mydb;Integrated Security=True");
         cn.Open();
        SqlCommand cm = new SqlCommand("Insert into TableDate_Time (DateTime ) values (@DateTime)");


        cm.Parameters.Add("@DateTime", SqlDbType.DateTime);
        cm.Parameters["@DateTime"].Value = DateTime.Now;  
         cm.Connection = cn;
         cm.ExecuteNonQuery();

     // something like:  var varID = the current myID value

   }

My Question is: How can I save the last row value of myID column into a variable whenever I click the button? any idea? Thank you

In Sql Server (and other database systems) you could pass two commands in the same text. Now T-SQL allows you to get back the last IDENTITY value generated for your connection using the command "SELECT SCOPE_IDENTITY()".

Thus your code will be

private void button1_Click(object sender, EventArgs e)
{
     string cmdText = @"Insert into TableDate_Time 
                       (DateTime ) values (@DateTime);
                       SELECT SCOPE_IDENTITY()");
     using(SqlConnection cn = new SqlConnection("...."))
     using(SqlCommand cm = new SqlCommand(cmdText, cn))
     {
         cn.Open();
         cm.Parameters.Add("@DateTime", SqlDbType.DateTime);
         cm.Parameters["@DateTime"].Value = DateTime.Now;  
         int id = Convert.ToInt32(cm.ExecuteScalar());
         .... 
     }
}

Instead of ExecuteNonQuery , call ExecuteScalar that returns the first column of the first row in the last command executed here (The SELECT). Note that it is a good practice to enclose every disposable object like the connection and the command in a using statement to have a correct exit path for your code in case of exceptions (one that doesn't forget to dispose these objects)

EDIT

If your ID column is not an IDENTITY column but an uniqueidentifier there are more problems. I suppose that your table has defined a default for the column ID using the NEWID() function of T-SQL

In this case you need to change your query to

private void button1_Click(object sender, EventArgs e)
{
     string cmdText = @"Insert into TableDate_Time 
                       (DateTime ) OUTPUT INSERTED.myID values (@DateTime)";
     using(SqlConnection cn = new SqlConnection("...."))
     using(SqlCommand cm = new SqlCommand(cmdText, cn))
     {
         cn.Open();
         cm.Parameters.Add("@DateTime", SqlDbType.DateTime);
         cm.Parameters["@DateTime"].Value = DateTime.Now;  
         Guid id = (Guid)cm.ExecuteScalar();
         .... 
     }
}

Assuming that the new ID is generated in the database via a column default, you could use the OUTPUT clause to return the ID of the new record:

private void button1_Click(object sender, EventArgs e)
{

    SqlConnection cn = new SqlConnection("Data Source=PCN-TOSH;Initial Catalog=mydb;Integrated Security=True");
    cn.Open();
    SqlCommand cm = new SqlCommand("INSERT INTO TableDate_Time (DateTime) OUTPUT inserted.myID VALUES (@DateTime)");

    cm.Parameters.Add("@DateTime", SqlDbType.DateTime);
    cm.Parameters["@DateTime"].Value = DateTime.Now;  
    cm.Connection = cn;
    Guid newID = (Guid)cm.ExecuteScalar();
}

Some other things to consider that are not germane you your problem:

  • Don't put direct SQL logic in a button click event handler - use a separate class for data management
  • Wrap you commands and connections in using blocks so that they are closed in a timely fashion, even if there is an exception.

That's easy. Just add the following code:

private void button1_Click(object sender, EventArgs e)
    {

 SqlConnection cn = new SqlConnection("Data Source=PCN-TOSH;Initial Catalog=mydb;Integrated Security=True");
         cn.Open();
        SqlCommand cm = new SqlCommand("Insert into TableDate_Time (DateTime ) values (@DateTime)");


        cm.Parameters.Add("@DateTime", SqlDbType.DateTime);
        cm.Parameters["@DateTime"].Value = DateTime.Now;  
         cm.Connection = cn;
         int returnValue = 0;
         SqlParameter param = new SqlParameter();
         param.ParameterName = "ReturnParameter";
         param.Direction = ParameterDirection.ReturnValue;
         cm.Parameters.Add(param);

         cm.Connection.Open();
         cm.ExecuteNonQuery();    
   }

And in your stored procedure (or sql query) add:

DECLARE @ID int = (Select SCOPE_IDENTITY())

RETURN @ID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM