这个问题在这里已经有了答案:插入多行而不重复语句的“INSERT INTO ...”部分? (16 个回答) 8 年前关闭。
我要一次插入多组数据,比如 4 行。我的表有三列:Person
、Id
和 Office
。
INSERT INTO MyTable VALUES ("John", 123, "Lloyds Office");
INSERT INTO MyTable VALUES ("Jane", 124, "Lloyds Office");
INSERT INTO MyTable VALUES ("Billy", 125, "London Office");
INSERT INTO MyTable VALUES ("Miranda", 126, "Bristol Office");
我可以在一个 SQL 语句中插入所有 4 行吗?
insert into profiles (name, description) select first, 'Auto-generated' from users
您似乎混淆了插入和更新语句,它们是不同的野兽。
insert ... select
语法,它会为您提供所需的一切,并且尽可能灵活。 dev.mysql.com/doc/refman/5.5/en/insert.html
在 SQL Server 2008 中,您可以使用单个 SQL INSERT 语句插入多行。
INSERT INTO MyTable ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )
作为参考,请查看 MOC 课程 2778A - 在 SQL Server 2008 中编写 SQL 查询。
例如:
INSERT INTO MyTable
( Column1, Column2, Column3 )
VALUES
('John', 123, 'Lloyds Office'),
('Jane', 124, 'Lloyds Office'),
('Billy', 125, 'London Office'),
('Miranda', 126, 'Bristol Office');
如果要插入单个表,则可以这样编写查询(可能仅在 MySQL 中):
INSERT INTO table1 (First, Last)
VALUES
('Fred', 'Smith'),
('John', 'Smith'),
('Michael', 'Smith'),
('Robert', 'Smith');
注意:此答案适用于 SQL Server 2005。对于 SQL Server 2008 及更高版本,如其他答案所示,有更好的方法。
您可以使用 INSERT with SELECT UNION ALL:
INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
...
不过,仅适用于小型数据集,这对您的 4 条记录应该没问题。
'Before date: ' + date2str(GETDATE()) + ' after date.'
我知道 date2str 有点奇怪,但在我的数据库中是特殊语法。
使用 VALUES
语法的 INSERT
语句可以插入多行。为此,请包含多个列值列表,每个列表都包含在括号中并用逗号分隔。
例子:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
不定期副业成功案例分享
VALUES
子句中的最大行数是 1000”。限制为 1000 行的不是INSERT
语句。