Insert multiple rows of data in a single SQL statement
本问题已经有最佳答案,请猛点这里访问。
我有一组数据要一次插入
1 2 3 | INSERT INTO MyTable VALUES ("John","Doe", 1234567890,"employee",""); INSERT INTO MyTable VALUES ("Susen","Gupta", 1234567890,"leander"); INSERT INTO MyTable VALUES ("Karn","Share", 1234567890,"employee","home"); |
我想在一个SQL语句中插入多行。 并且可以使用不同数量的值来实现它。
自SQL-92以来,多行插入已成为SQL标准的一部分,许多现代DBMS都支持它。 这将允许你做以下事情:
1 2 3 4 5 | INSERT INTO MyTable ( Name, Id, Location) VALUES ('John', 123, 'Lloyds Office'), ('Jane', 124, 'Lloyds Office'), ('Billy', 125, 'London Office'), ('Miranda', 126, 'Bristol Office'); |
您会注意到我在那里使用完整形式的
如果您的特定DBMS不支持它,您可以将其作为依赖于DBMS的事务的一部分来执行,但基本上如下所示:
1 2 3 4 5 6 | BEGIN TRANSACTION; INSERT INTO MyTable (Name,Id,Location) VALUES ('John',123,'Lloyds Office'); INSERT INTO MyTable (Name,Id,Location) VALUES ('Jane',124,'Lloyds Office'), INSERT INTO MyTable (Name,Id,Location) VALUES ('Billy',125,'London Office'), INSERT INTO MyTable (Name,Id,Location) VALUES ('Miranda',126,'Bristol Office'); commit TRANSACTION; |
这使操作成为原子,插入所有值或插入none。
是的,你可以,但它取决于你正在使用的SQL味道:),例如在mysql和sqlserver中:
1 2 | INSERT INTO TABLE ( col1, col2 ) VALUES ( val1_1, val1_2 ), ( val2_1, val2_2 ), ( val3_1, val3_2 ); |
但是在oracle中:
1 2 3 4 5 6 7 8 | INSERT ALL INTO TABLE (col1, col2, col3) VALUES ('val1_1', 'val1_2', 'val1_3') INTO TABLE (col1, col2, col3) VALUES ('val2_1', 'val2_2', 'val2_3') INTO TABLE (col1, col2, col3) VALUES ('val3_1', 'val3_2', 'val3_3') . . . SELECT 1 FROM DUAL; |
在SQL Server中,您可以这样做:
1 2 3 4 | INSERT INTO MyTable VALUES ("John", 123,"Lloyds Office"), ("Jane", 124,"Lloyds Office"), ("Billy", 125,"London Office"), ("Miranda", 126,"Bristol Office") |