简体   繁体   中英

Select and Insert From two Sql Tables.C#

my code dosent works. pls correct me.

Example I want to say take 2 values from (COlumn*) Where .... and 2 values from (COlumn*) Where ....

con.Open();
SqlCommand cmd = new SqlCommand
("INSERT INTO temp_rent(parts,size,color,quantities,barcode,name,mobile,code) select 
parts,size,color,quantities,barcode from inventory where barcode = ('" + textBox4.Text + "')
 select name,mobile,code from customermaster where code= '" + textBox1.Text + "')", con);
                    cmd.ExecuteNonQuery();
                    con.Close();

Here is my approach:

First In visual studio (2015) I have added a data source. Please take into account that different versions of visual studio have different ways to add data source. So in VS2015 click

  • project
  • add new data source database
  • dataset
  • configure Your connection to the db
  • select tables You will be working with
  • name the DataSet (mine is SO_testDataSet)

After finish, You will have a ...DataSet.xsd in the project. Double click on it.

Here You will see the tables You imported from the database. right click on the header of temp_rent, because You want to create a query that will insert into temp_rent at the end.

  • Add
  • Query
  • Here You can use "Use SQL statements" or "Create new stored procedure". I suggest the second one, but for the simplicity use the first now.
  • Insert
  • Paste the following into the textbox. Check it in the Query Builder if You like.

     INSERT INTO temp_rent (parts, size, color, quantities, barcode, name, mobile, code) SELECT i.parts, i.size, i.color, i.quantities, i.barcode, cm.name, cm.mobile, cm.code FROM inventory AS i CROSS JOIN customermaster AS cm WHERE (cm.code = @code) AND (i.barcode = @barcode) 
  • Name Your Query (mine is InsertQuery)

Finish, save. In the query You can see there is cross join, because inventory and customermasters are not joined by a column. It's a simple Cartesian product. You could use also FROM inventory, customermaster or FROM inventory JOIN customermaster (because ON is optional). We can also see the @code and @barcode are placeholders for the parametrized query.

In the code You can use the added query like this:

SO_testDataSetTableAdapters.temp_rentTableAdapter adapter = new SO_testDataSetTableAdapters.temp_rentTableAdapter();
// I assume that code and barcode are the type of int in the database.
adapter.InsertQuery(int.Parse(textBox1.Text), int.Parse(textBox4.Text));

If the textboxes are containing some evil string, the int.Parse will throw exception, because the evil string cannot be parsed as int (for the sake of defending from sql injection).

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