在sql中插入语句 [英] insert statement in sql

查看:93
本文介绍了在sql中插入语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含5个表格的数据库。

我正在创建一个提交表单,它将在表格中存储相应的值。

我打算提供一个提交按钮在使用c#的表单中。

但我对如何通过单击按钮将数据插入多个表格感到困惑。

解决方案

< pre lang =cs> con1 =新SqlConnection( server =& srv_nm& < span class =code-string> ; uid =& usr_id& ; pwd =& pwd& ; database =& db)
con1.Open()
cm = new SqlCommand( 插入表名值('& textbox1.text& '),con1)
cm.executeNonQuery()







类似地你在BUTTON ACTION事件中放入具有不同表名的其他INSERT STATEMENT。

这样当你点击表格中的按钮时全部值反映在不同的表中。


正如Christian所说,你只需将插入语句一个接一个地写出来。由于您要将数据插入多个表格,请确保使用的是 Transcations [ ^ ]

如果您需要将一个表的主键插入另一个表中,请使用 SCOPE_IDENTITY(Transact-SQL) [ ^ ]检索自动生成的主键值。下面是将数据插入table1的示例,主键值存储在变量中,然后插入到table2中



 < span class =code-keyword> 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)
- 您可以拥有任意数量的插入语句


COMMIT TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
- 错误处理
END CATCH


使用事务进行批处理和使用SCOPEIDENTITY()检查是否插入


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.

解决方案

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.


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

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  


Use Transaction for batch processing and use SCOPEIDENTITY() to check whether it's inserted or not


这篇关于在sql中插入语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆