简体   繁体   English

将数据插入SQL表

[英]Insert Data into SQL Table

The Data in my DataTable is like 我的数据表中的数据就像

ID ContactName1  Designation1 ContactName2 Designation2
1  A             dummy        B            sam 

The Table structure of my Table is 我的表的表结构是

ID ContactName Designation

I am passing the values in the stored procedure as: 我将存储过程中的值传递为:

@ContactName1
@Designation1

@ContactName2
@Designation2

I want a single insert statement to insert the records. 我想要一个插入语句来插入记录。

How can I achieve this? 我该如何实现?

Assuming your ID primary key is set on auto-increment, and your table has three fields: 假设您的ID主键设置为自动递增,并且表具有三个字段:

INSERT INTO DataTable (ContactName, Designation) VALUES 
    (@ContactName1, @Designation1), 
    (@ContactName2, @Designation2);

As per the actual ID, if you don't have it on auto-increment, which judging from the comment on Ivan's response, you don't, you could actually get it using the MAX() statement: 根据实际的ID,如果您没有自动递增的ID,那么从对Ivan响应的评论来看,您就没有了,实际上可以使用MAX()语句获取它:

SELECT MAX(ID) AS max_id FROM DataTable

Given that it is in a stored procedure, why do you care whether it is one or two INSERT statements? 鉴于它在存储过程中,为什么还要关心它是一个还是两个INSERT语句? Clearly, two statements is trivial. 显然,有两个陈述是微不足道的。

Some DBMS allow you to list multiple values clauses in a single INSERT (@Ivan suggests this): 一些DBMS允许您在单个INSERT中列出多个value子句(@Ivan建议这样做):

INSERT INTO Table(ID, ContactName, Designation)
    VALUES(1, @ContactName1, @Designation1)
    VALUES(1, @ContactName2, @Designation2);

I'm not certain whether a comma is needed between the values lists. 我不确定值列表之间是否需要逗号。 I'm also not clear whether the two records in Table are allowed to have the same ID, nor how the ID is determined - that is probably some auto-increment stuff, and different DBMS do that differently too. 我也不清楚表中的两个记录是否具有相同的ID,也不清楚ID是如何确定的-这可能是一些自动递增的内容,并且不同的DBMS所做的也不同。

If your DBMS does not support multiple VALUES clauses in a single INSERT statement, then you will be best off accepting two INSERT statements. 如果您的DBMS在单个INSERT语句中不支持多个VALUES子句,那么最好是接受两个INSERT语句。 If atomicity is an issue, you can consider transactions - though if this is just a part of a bigger transaction, ROLLBACK on error, in particular, would be a problem. 如果原子性是一个问题,则可以考虑进行事务处理-尽管如果这只是较大事务的一部分,则特别是发生错误时回滚是一个问题。 If your DBMS supports SAVEPOINTS, then the procedure could establish a savepoint on entry, and commit or rollback to the savepoint on exit. 如果您的DBMS支持SAVEPOINTS,则该过程可以在条目上建立一个保存点,并在退出时提交或回滚到该保存点。

INSERT INTO TABLENAME VALUES(GIVE VALUE ACCORDING TO NUMBER AND ORDER SEPARATED BY COMMA) 插入表名值(根据数字和订单号提供的值,以逗号分隔)

EX:- EX: -

INSERT INTO TABLENAME VALUES(1,'INDIA')

HERE IS TWO COLUMN SN & COUNTRY 这是两个列的SN和国家/地区

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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