基础语法
 
-- 查看数据表
select * from Student
 
-- 使用Sql查询数据
 
--1、查询表中所有类容
Select * From TableName
 
--2、查询表中指定字段类容
Select ColumnName,…, From TableName
 
Select stuName,stuNo,stuSex From stuInfo
 
--3、带Where条件的查询
Select *|ColumnName From TableName Where condition
 
select * From stuInfo where stuSex='女'
 
--4、带排序的查询(Order By ColumnName)
-- 语法: Select *|ColumnName From TableName Order By ColumnName Desc|Asc
 
Select * From stuInfo Order By stuAge,stuSeat desc
 
-- 5、选择指定数量的记录,通常配合order By使用
-- 语法: Select Top num *|ColumnName From TableName 
-- 语法: Select Top num *|ColumnName From TableName Order By Desc|Asc
Select Top 2 * From stuInfo Order By stuAge Desc
 
-- 6、分组查询 Group By
-- 分组查询中包含的列必须包含在聚合函数或 GROUP BY 子句中
Select * From stuInfo
Select stuSex, Max(stuAge) As '平均年龄' From stuInfo Group By stuSex
 
--7、对分组后的结果进行过滤
-- having(相当于Where)
Select * From stuInfo
Select stuSex, Avg(stuAge) As '平均年龄' From stuInfo Group By stuSex having Avg(stuAge)>20
 
--8、Group By 配合 Where 使用
Select * From stuInfo
Select stuSex, Avg(stuAge) As '平均年龄' From stuInfo where stuAge > 18 Group By stuSex having Avg(stuAge)>20 
 
 
-----------------------------------------------------------
--使用Sql插入数据
--1、不指定列插入数据
语法:Insert Into TableName Values(值列表)
Insert Into stuInfo Values('小八','S25311','男',24,'北京')
 
Select * from stuInfo
 
-- 2、指定列名对数据插入
--语法:Insert Into TableName(列名列表) Values(值列表)
--注意:列名列表顺序可自己指定,但值列表的顺序应该和列名列表相同。
 
Insert Into stuInfo(stuName,stuNo,stuSex,stuAddress,stuAge) Values('小九','S25312','男','上海',25)
 
select * from stuInfo
 
--3、一次插入多条记录
--1) Insert Into TableName(列名类表) Select…From  插入到现存的表中
--注意:列名的数据类型,个数必须相同
 
Insert Into stuInfoCopy(stuName,stuNo,stuSex,stuAge,stuSeat,stuAddress)
Select * From stuInfo
 
Select * From stuInfoCopy
 
--3、一次插入多条记录
--2) Select 列名列表 Into 新表名 From SourceTable 插入到现存的表中
--注意:列名的数据类型,个数必须相同,新表必须不存在
Select Identity(int,1,1) As 'ID',stuName,stuNo,stuSex,stuAge,stuAddress 
Into #temp
From stuInfo
 
select * from #temp
 
--3、一次插入多行记录
--3)使用Union合并数据行
Insert #temp(stuName,stuNo,stuSex,stuAge,stuAddress)
Select '宝贝','S25318','男',22,'湖北' Union
Select '宝贝2','S25318','女',23,'湖南' 
 
select * from #temp
 
 
--4、更改数据
--语法: Update TableName Set ColumnName=值 where Condititon
 
Update #temp Set stuName = '宝贝3' Where stuName = '宝贝'
 
Select * from #temp
 
--5删除数据
-- 语法: Delete From TableName Where Condition
Delete From #temp Where Id=8
 
Select * From #temp
 
--5删除数据
--语法: Truncate Table TableName(在删除表中所有数据时,比Delete效率高,但不能
--删除包含外键约束的表
 
Truncate Table stuMarks
 
 
-- Where 条件种类
--1、ColumnName Between 低值 And 高值
Select * from stuInfo Where stuAge Between 20 And 25
 
--2、And Or Not(与,或,非)
 
--3、In(值列表)
Select * from stuInfo Where stuAge IN (21,25)
 
--4、Like(模糊查询)
-- % 表示任意数量字符 _ 一个字符 [] 一个范围 [^]不在某个范围
Select * from stuInfo Where stuName like '小%'