我有多组数据要一次性插入,比如说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行吗?
在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条记录来说应该没问题。