我知道我几年前就这样做过,但我不记得语法了,而且由于调出大量关于“批量导入”的帮助文档和文章,我在任何地方都找不到它。
这是我想做的,但语法不完全正确…拜托,以前做过这件事的人帮帮我吧:)
INSERT INTO dbo.MyTable (ID, Name)
VALUES (123, 'Timmy'),
(124, 'Jonny'),
(125, 'Sally')
我知道这和正确的语法很接近。我可能需要"散装"这个词,我不记得了。任何想法?
我需要这个SQL Server 2005数据库。我试过这段代码,但没有效果:
DECLARE @blah TABLE
(
ID INT NOT NULL PRIMARY KEY,
Name VARCHAR(100) NOT NULL
)
INSERT INTO @blah (ID, Name)
VALUES (123, 'Timmy')
VALUES (124, 'Jonny')
VALUES (125, 'Sally')
SELECT * FROM @blah
我在关键字“值”附近得到不正确的语法。
使用INSERT INTO…VALUES语法,比如Daniel Vassallo的回答
有一个恼人的限制:
从MSDN
通过直接在VALUES列表中插入行可以构造的最大行数是1000
省略这个限制最简单的方法是使用派生表,如:
INSERT INTO dbo.Mytable(ID, Name)
SELECT ID, Name
FROM (
VALUES (1, 'a'),
(2, 'b'),
--...
-- more than 1000 rows
)sub (ID, Name);
现场演示
这将从SQL Server 2008+开始工作
这里的其他人建议使用一些多记录语法。为此,我建议您先插入一个临时表,然后从那里插入您的主表。
这样做的原因是,从查询中加载数据可能会花费更长的时间,最终锁定表或页的时间可能会超过所需的时间,这会降低对该表运行的其他查询的速度。
-- Make a temp table with the needed columns
select top 0 *
into #temp
from MyTable (nolock)
-- load data into it at your leisure (nobody else is waiting for this table or these pages)
insert #temp (ID, Name)
values (123, 'Timmy'),
(124, 'Jonny'),
(125, 'Sally')
-- Now that all the data is in SQL, copy it over to the real table. This runs much faster in most cases.
insert MyTable (ID, Name)
select ID, Name
from #temp
-- cleanup
drop table #temp
此外,您的id可能应该是identity(1,1),在绝大多数情况下,您可能不应该插入它们。让SQL为您决定这些事情。
这对于SQL Server 2008来说是OK的。对于SS2005及更早的版本,您需要重复VALUES语句。
INSERT INTO dbo.MyTable (ID, Name)
VALUES (123, 'Timmy')
VALUES (124, 'Jonny')
VALUES (125, 'Sally')
编辑:我的错。在SS2005中,您必须对每一行重复INSERT INTO。
INSERT INTO dbo.MyTable (ID, Name)
VALUES (123, 'Timmy')
INSERT INTO dbo.MyTable (ID, Name)
VALUES (124, 'Jonny')
INSERT INTO dbo.MyTable (ID, Name)
VALUES (125, 'Sally')
在SQL Server中使用XML插入多行会更容易,否则会变得非常乏味。
查看完整的文章与代码解释在这里http://www.cyberminds.co.uk/blog/articles/how-to-insert-multiple-rows-in-sql-server.aspx
将以下代码复制到sql server中以查看示例。
declare @test nvarchar(max)
set @test = '<topic><dialog id="1" answerId="41">
<comment>comment 1</comment>
</dialog>
<dialog id="2" answerId="42" >
<comment>comment 2</comment>
</dialog>
<dialog id="3" answerId="43" >
<comment>comment 3</comment>
</dialog>
</topic>'
declare @testxml xml
set @testxml = cast(@test as xml)
declare @answerTemp Table(dialogid int, answerid int, comment varchar(1000))
insert @answerTemp
SELECT ParamValues.ID.value('@id','int') ,
ParamValues.ID.value('@answerId','int') ,
ParamValues.ID.value('(comment)[1]','VARCHAR(1000)')
FROM @testxml.nodes('topic/dialog') as ParamValues(ID)
你的语法基本适用于SQL Server 2008(但不适用于SQL Server 20051):
CREATE TABLE MyTable (id int, name char(10));
INSERT INTO MyTable (id, name) VALUES (1, 'Bob'), (2, 'Peter'), (3, 'Joe');
SELECT * FROM MyTable;
id | name
---+---------
1 | Bob
2 | Peter
3 | Joe
当回答这个问题时,并没有明确表示这个问题指的是SQL Server 2005。我把这个答案留在这里,因为我相信它仍然是相关的。