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

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

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

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


当前回答

在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');

其他回答

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

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 (Transact-SQL) (SQL Server 2005),不能省略INSERT INTO dbo。废话,每次都必须指定它或使用另一种语法/方法,

我一直在使用以下方法:

INSERT INTO [TableName] (ID, Name)
values (NEWID(), NEWID())
GO 10

它将为ID和Name添加10行具有唯一guid的行。

注意:不要以';'结束最后一行(GO 10),因为它将抛出错误:发生了致命的脚本错误。解析GO时遇到不正确的语法。

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

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

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