SQL插入多行

问题描述 投票:32回答:6

我想在一个表中插入多行。如何使用单个插入语句执行此操作?

sql
6个回答
71
投票

将要插入括号/括号(value1, value2, value3)的每一行值换行,并用逗号分隔括号/括号,以便插入到表中。

INSERT INTO example
VALUES
  (100, 'Name 1', 'Value 1', 'Other 1'),
  (101, 'Name 2', 'Value 2', 'Other 2'),
  (102, 'Name 3', 'Value 3', 'Other 3'),
  (103, 'Name 4', 'Value 4', 'Other 4');

15
投票

您可以使用SQL批量插入语句

BULK INSERT TableName
FROM 'filePath'
WITH
(
  FIELDTERMINATOR = '','',
  ROWTERMINATOR = ''\n'',
  ROWS_PER_BATCH = 10000, 
  FIRSTROW = 2,
  TABLOCK
)

更多参考检查

https://www.google.co.in/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=sql%20bulk%20insert

您也可以批量插入代码中的数据

请检查以下链接:

http://www.codeproject.com/Articles/439843/Handling-BULK-Data-insert-from-CSV-to-SQL-Server


12
投票
1--> {Simple Insertion when table column sequence is known}
    Insert into Table1
    values(1,2,...)

2--> {Simple insertion mention column}  
    Insert into Table1(col2,col4)
    values(1,2)

3--> {bulk insertion when num of selected collumns of a table(#table2) are equal to Insertion table(Table1) }   
    Insert into Table1 {Column sequence}
    Select * -- column sequence should be same.
       from #table2

4--> {bulk insertion when you want to insert only into desired column of a table(table1)}
    Insert into Table1 (Column1,Column2 ....Desired Column from Table1)  
    Select Column1,Column2..desired column from #table2


3
投票

您可以使用UNION All子句在表中执行多个插入。

例如:

INSERT INTO dbo.MyTable (ID, Name)
SELECT 123, 'Timmy'
UNION ALL
SELECT 124, 'Jonny'
UNION ALL
SELECT 125, 'Sally'

Check here


2
投票

对于MSSQL,有两种方法:(考虑您有'用户'表,下面两个示例都使用此表为例)

1)如果需要在users表中插入不同的值。然后你可以写如下语句:

    INSERT INTO USERS VALUES
(2, 'Michael', 'Blythe'),
(3, 'Linda', 'Mitchell'),
(4, 'Jillian', 'Carson'),
(5, 'Garrett', 'Vargas');

2)另一种情况,如果你需要为所有行插入相同的值(例如,你需要在这里插入10行)。然后你可以使用下面的示例声明:

    INSERT INTO USERS VALUES
(2, 'Michael', 'Blythe')
GO 10

希望这可以帮助。

© www.soinside.com 2019 - 2024. All rights reserved.