Click here to Skip to main content
15,893,337 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a database with 5 tables.
I am creating a submit form which will store corresponding values in the tables.
I am planning to provide a submit button in the form using c#.
But i am a bit confused about how to insert data into multiple tables by clicking button.
Posted
Comments
Sunny_Kumar_ 18-Dec-12 4:11am    
share what you've tried yet and please elaborate what exactly you want to do? Do you want to insert the same value in 5 tables concurrently, or one after the other or anything else like that.

C#
con1 = New SqlConnection("server=" & srv_nm & ";uid=" & usr_id & ";pwd=" & pwd & ";database=" & db)
           con1.Open()
cm=new SqlCommand("insert into tablename values('" & textbox1.text & "')",con1)
cm.executeNonQuery()



Similarly You put Other INSERT STATEMENT with different table name here in the BUTTON ACTION Event.
So that When You click on the Button in the form All the values are reflected in different table.
 
Share this answer
 
As Christian said you just write the insert statements one below the other. Since you are inserting data into multiple table make sure you are using Transcations[^]
If you need the Primary key of one table to be inserted into another table use SCOPE_IDENTITY (Transact-SQL)[^] to retrieve the autogenerated primary key value. Below is a sample where data is inserted into table1, the primary key value is stored in a variable and then inserted into table2

SQL
BEGIN TRY  
  BEGIN TRANSACTION  

    
      DECLARE @PK_Table1 INT
      INSERT INTO table1 (Col1, col2,..., coln) VALUES (value1, value2,..., valuen)
      SET @PK_Table1 = SCOPE_IDENTITY()   

      INSERT INTO table2 (Col1, col2) VALUES (@PK_Table1, value3)
       --You can have as many insert statements as you like

  
  COMMIT TRANSACTION  
 END TRY  
 BEGIN CATCH  
  ROLLBACK TRANSACTION  
  --Error handling
 END CATCH  
 
Share this answer
 
Use Transaction for batch processing and use SCOPEIDENTITY() to check whether it's inserted or not
 
Share this answer
 
You write insert statements for whatever data you need to insert. If you like, you can put them all in a stored proc, so you only make one call.
 
Share this answer
 
Comments
Member 9581909 19-Dec-12 22:56pm    
thanks Christian...i am gonna try this way...If i get stuck somewhere...will surely get back to you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900