title: SQL query result to C# Variable
body: <p>I'm trying to pull data from an SQL variable in C# to use in another SQL query.</p>
  
  <p>Basically I have a for loop that is running through a datagrid and inserting the data into a table which I need to be linked to @DataID in this query below.  As it is in a different query I can't access it so I want to pull it out into a var.</p>
  
  <p>What's the best way to go about this? already searched lots of options and not coming up with anything that works</p>
  
  <p>The help is appreciated!</p>
  
  <p>Cheers</p>
  
  <pre><code>string dartBoxQuery = @"DECLARE @DataID int;
  INSERT INTO DartBox (DartBoxNumber, ReturnDate, Comments)
  VALUES (@dbn, @rtndate, @cmmts)
  SELECT @DataID = scope_identity();";
  
  // set up the command before exec
  SqlCommand cmd = new SqlCommand(dartBoxQuery, con);
  
  //set parameters
  cmd.Parameters.AddWithValue("@rtndate", dateTimePicker1.Text);
  cmd.Parameters.AddWithValue("@dbn", textBox1.Text);
  cmd.Parameters.AddWithValue("@cmmts", textBox2.Text);
  
  // call SQL connection
  con.Open();
  // execute above query
  cmd.ExecuteNonQuery();
  
  //close connection
  con.Close();
  </code></pre>