SQL中一次插入多條數據


SQL中insert一次可以插入一條數據,我們有三種方法可以一次性插入多條數據。

1.

語法:select 字段列表 into 新表 from 源表

注意事項:此種方法新表是系統自動創建,語句執行前不可以存在新表,並且新表只能保留源表的標識列特性,其他約束不能保留。

若只需要源表的數據結構,我們可以在語句中添加(top 0)

2.

語法:insert into 目的表 select 字段列表 from 源表

注意事項:此種方法目的表必須在語句執行前存在,並且每一列要與源表對應。

在此處還有一些有趣的問題,當我使用以下代碼來插入多條數據時:

select top 0 * into newstudent from  student
insert into newstudent select * from student

這里會發生這樣的報錯:

因為NewClass表中ClassId為標識列,所以我們不能插入值。

我們的解決辦法如下:

select top 0 * into newstudent from  student
set identity_insert newstudent on
insert into newstudent (classid,classname) select * from student

我們把newstudent 的標識列插入寫為顯示的,並且添加了列名字段便可以插入了。

之后我們再創建一個新的NewClass2:

select top 0 *into NewClass2 from MyClass
set identity_insert NewClass2 on
insert into NewClass2(ClassId,ClassName) select* from MyClass

此時還會報錯,這是因為我們之前設置了newclass的標識列插入為on,我們必須先關閉后才可以往newclass2插入值,代碼如下:

select top 0 *into NewClass2 from MyClass
set identity_insert newclass off
set identity_insert NewClass2 on
insert into NewClass2(ClassId,ClassName) select* from MyClass

至此我們解決了使用第二種方法一次插入多條數據。

3.

語法:insert into 表(字段列名) select 值 union select值

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM