Fork me on GitHub

SQL Sever 基础语法(增)

SQL Sever  插入(Insert)基础语法详解

在SQL中,向表中插入数据是最基础的,任何对数据处理的基础就是数据库有数据,对于SQL而言,向表中插入数据有多种方法,本文列举3种:

(一)

标准插入

语法:

 1 insert into table1(field1,field2) values(value1,value2) 

 INSERT INTO dbo.Student(STUdentID,UserName, PassWord,StuName,StuSex,Stuaddress,StuPhone1, StuPhone2)
values( 'STU12021A0000006','201740450106','666666','李华','男','中国省','17723131220','17123213060')

 table1:表名 ,value1:字段值field1:字段名  

注:插入时,values(value1,value2) 要对应table1(field1,field2)

(二)

使用select 语句(单条)插入

1 INSERT INTO dbo.Student(STUdentID,UserName, PassWord,StuName,StuSex,Stuaddress,StuPhone1, StuPhone2)
2 SELECT 'STU12021A0000006','201740450106','666666','李华','','中国省','17723131220','17123213060'

使用select 语句(多条)插入

1 INSERT INTO dbo.Student(STUdentID,UserName, PassWord,StuName,StuSex,Stuaddress,StuPhone1, StuPhone2)
2 SELECT 'STU12021A0000006','201740450106','666666','李华','','中国省','17723131220','17123213060'
3 UNION ALL 
4 SELECT 'STU12021A0000007','201740450107','666666','李华2','','中国省2','17723131220','17123213060'
5 UNION ALL 
6 SELECT 'STU12021A0000008','201740450108','666666','李华2','','中国省2','17723131220','17123213060'

注:UNION ALL 语法使用时,select 的第一个结果集和第二个结果集上下文要匹配(每一列的类型),否则报错类型不匹配

 

使用集合插入:

 1 DECLARE @temp TABLE (
 2         LotId INT NULL,
 3         LotSN NVARCHAR(50) NULL,
 4         MacAddress NVARCHAR(50) NULL
 5     )
 6 INSERT INTO @temp
 7 (
 8     LotId,
 9     LotSN,
10     MacAddress
11 )
12 VALUES
13 ('1',N'H90X6231205C00671',N'2825364439CC'),
14 ('1',N'H90X6231205C00672',N'28253645BF3F'),
15 ('1',N'H90X6231205C00673',N'2825364439E8'),
16 ('1',N'H90X6231205C00674',N'2825364439D4'),
17 ('1',N'H90X6231205C00675',N'2825364439D5'),
18 ('1',N'H90X6231205C00676',N'2825364439D6')
View Code

 

 (三)

从另一个表获取数据插入当前操作的表

语法: insert into table1(field1,field2)select(value1,value2) FROM table2 WHERE value1='条件'

1 INSERT INTO dbo.test2( name) SELECT StuName FROM dbo.Student WHERE  StuName='李华'

 

 能帮朋友解决问题的记得给个关注支持一下,以后将多多分享SQL SERVER 相关知识

posted @ 2021-11-09 09:18  酒笙匿清栀  阅读(147)  评论(0编辑  收藏  举报