我知道我几年前就这样做过,但我不记得语法了,而且由于调出大量关于“批量导入”的帮助文档和文章,我在任何地方都找不到它。

这是我想做的,但语法不完全正确…拜托,以前做过这件事的人帮帮我吧:)

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

我在关键字“值”附近得到不正确的语法。


当前回答

你的语法基本适用于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。我把这个答案留在这里,因为我相信它仍然是相关的。

其他回答

USE YourDB
GO
INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
UNION ALL
SELECT 'Fourth' ,4
UNION ALL
SELECT 'Fifth' ,5
GO

或者你可以用另一种方法

INSERT INTO MyTable (FirstCol, SecondCol)
VALUES 
('First',1),
('Second',2),
('Third',3),
('Fourth',4),
('Fifth',5)

你的语法基本适用于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。我把这个答案留在这里,因为我相信它仍然是相关的。

在PostgreSQL中,你可以这样做;

2列表的通用示例;

INSERT INTO <table_name_here>
    (<column_1>, <column_2>)
VALUES
    (<column_1_value>, <column_2_value>),
    (<column_1_value>, <column_2_value>),
    (<column_1_value>, <column_2_value>),
    ...
    (<column_1_value>, <column_2_value>);

在这里查看真实世界的例子;

A -创建表

CREATE TABLE Worker
(
    id serial primary key,
    code varchar(256) null,
    message text null
);

插入批量值

INSERT INTO Worker
    (code, message)
VALUES
    ('a1', 'this is the first message'),
    ('a2', 'this is the second message'),
    ('a3', 'this is the third message'),
    ('a4', 'this is the fourth message'),
    ('a5', 'this is the fifth message'),
    ('a6', 'this is the sixth message');

你可以这样做(很难看,但很有效):

INSERT INTO dbo.MyTable (ID, Name) 
select * from
(
 select 123, 'Timmy'
  union all
 select 124, 'Jonny' 
  union all
 select 125, 'Sally'
 ...
) x

这对于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')