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

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

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 dbo.MyTable (ID, Name) 
select * from
(
 select 123, 'Timmy'
  union all
 select 124, 'Jonny' 
  union all
 select 125, 'Sally'
 ...
) x

其他回答

创建一个表以同时插入多条记录。

CREATE TABLE TEST 
(
    id numeric(10,0),
    name varchar(40)
)

之后创建一个存储过程来插入多条记录。

CREATE PROCEDURE AddMultiple
(
    @category varchar(2500)
)
as
BEGIN

declare @categoryXML xml;
set @categoryXML = cast(@category as xml);

    INSERT INTO TEST(id, name)
    SELECT
        x.v.value('@user','VARCHAR(50)'),
        x.v.value('.','VARCHAR(50)')
    FROM @categoryXML.nodes('/categories/category') x(v)
END
GO

执行过程

EXEC AddMultiple @category = '<categories> 
                                  <category user="13284">1</category> 
                                  <category user="132">2</category>
                              </categories>';

然后通过查询表进行检查。

select * from TEST;

如果你的数据已经在你的数据库中,你可以这样做:

INSERT INTO MyTable(ID, Name)
SELECT ID, NAME FROM OtherTable

如果你需要硬编码数据,那么SQL 2008和以后的版本让你做以下…

INSERT INTO MyTable (Name, ID)
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 ID, Name FROM (
    SELECT 123, 'Timmy'
    UNION ALL
    SELECT 124, 'Jonny'
    UNION ALL
    SELECT 125, 'Sally'
) AS X (ID, Name)