2012-09-11 118 views
9

我想在單個表中插入多行。我怎樣才能做到這一點使用單一的插入語句?SQL插入多行

回答

35
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'); 
+0

這是MySQL的語法,不知道這是否是在通用的SQL接受。一些DBMS可能不支持這種語法。 – Konerak

+5

SQL Server也支持這種語法。 – fancyPants

+1

@Konerak [看到這個SQLFiddle](http://sqlfiddle.com/#!3/d314c/5) – hims056

2

您可以使用UNION All子句中的表執行多個插入。

例如:

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

Check here

4
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

您可以使用SQL BULK INSERT語句

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