)
二、删表
Drop Table Tbstudent
三、修改表结构
修改表结构时,一定要注意会不会与原来表中的数据有冲突
1、 增加字段 alter Table TbStudent Add TGender bit not null
2、 修改字段 alter Table tbstudent alter column TCardId varchar(18 ) not null 当表中有数据时,这里就不可以直接 not null,因为会与原来表中的数据有冲突
3、 删除字段 Alter Table Tbstudent Drop Column TAddress
4、 添加追主键约束 Alter Table TbStudent add constraint PK_Tbstudent_Tid primary key (Tid)
四、列的别名、列的重命名
Select
1.通过as Select TName as name,Tbirthday from Tbstudent
2.通过别名=列名 Select name =Tname ,Tbirthday from tbstudent
3.空格后直接写别名 Select Tname name ,Tbirthday from tbstudent
五、Union相关
1、合并结果集(要求两个结果集的列数必须相同,类型可以相互转换) select Tname ,TAddress from tbstudent
union
select TclassName , TclassDesc from tbclass
注意,Union是把后面结果集的数据并入了第一个。
2、union 和 union all的区别
union all 在联合的时候不会去掉重复数据
union 在联合的时候,会去掉重复的数据
六、Top、Distinct
1、Top
获取前几条数据,top一般都与order by连用
--只获前n条数据
select top 10 FName from MyStudent
--获取前n%的数据
select top 10 percent * from MyStudent
2、Distinct 去除重复数据
select distinct fclassid from newStudent
select distinct FGender from newStudent
select * from newStudent
select distinct fage from newStudent
where FGender='男'
--先distinct,再top
select distinct top 3 fclassid from MyStudent
七、分页查询
1、通过top来实现
--第n条的数据,每页5条
--1、先找已看过的数据
--2、从整个数据中排除已经看过的数据
select top 5* from Customers where CustomerId not in (select top (n-1)*5 CutomerId from Customers order by CutomerId asc) order by CustomeId asc
2、2005以后使用row_number()排名函数
select * from
(
select row_number() over (order by id ase) as Rn
) as Tbl
where Tbl.Rn between (4-1)*7+1 and 4*7
第一种:用页码pageIndex和页大小pageSize来控制页数。
declare @pageIndex int
declare @pageSize int
select top(@pageSize) * from dbo.HKSJ_Main where ID not in
(select top((@pageIndex-1)*@pageSize) ID from dbo.HKSJ_Main order by ID )
order by ID
第二种:用row_Number()配合开窗函数来完成。
Declare @pageIndex int
Declare @pageSize int
Select * from (
Select row_number() over(order by id) as r_num from user ) as u
Where u.r_num between (@pageIndex-1)*@pageSize and @pageIndex*@pageSize order by id;
4、分页存储过程
create proc usp_getdatabypage
@pageIndex int,
@pageSize int,
@count int output
as
begin
select SId, SName, SAge, SEmail, SBirthday, SGender,ROW_NUMBER() over(order by SId) as Rn
into #tmp_stu
from [T_Students]
select SId, SName, SAge, SEmail, SBirthday, SGender
from [#tmp_stu]
where Rn between ((@pageIndex-1)*@pageSize+1) and @pageIndex*@pageSize
select @count=COUNT(*) from [#tmp_stu]
end
八、子查询(感谢张怀晶组贡献)
概念:
把一个查询的结果放在另一个查询中使用,这个查询就叫做子查询。
子查询的基本分类:独立子查询和相关子查询。
独立子查询(Uncorrelated Sub-Query):可以独立运行的子查询。也叫非相关子查询。
相关子查询(Correlated Sub-Query):子查询中引用了父查询中的结果。
代码:
--用户信息表
CREATE TABLE USER
(
USERID INT NOT NULL,--用户id