黑马程序员—传智播客sql从入门到提高视频知识整理(2)

来源:互联网 发布:cs算法原理 编辑:程序博客网 时间:2024/05/15 03:40

---------------------- Windows Phone 7手机开发、.Net培训、期待与您交流! ----------------------

创建表、删除表可手工完成,也可执行SQL语句完成,创建表:
Create table tb_Student(id int not null,name nvarchar(50),age int null)
删除表:
Drop table tb_Student
更改表:Alter table tb_Student add grade int;(向student表中添加一个int类型的grade字段)

向表内插入数据用Insert,insert语句可以省略表名后的列名,例如:向主键id为Guid类型的表内插入数据为,
Insert into tb_Student(id,name,age) values(newid(),'aa',20);可以写为:
Insert into tb_Student values(newid(),'zz',20);  但是不推荐简写。
如果插入的列中有些字段值不确定,那么Insert是不指定那些列即可。可以给字段设置默认值。

更新使用Update,例如:Update tb_Student set name='nn',age=21;
也可加where判断,例如:Update tb_Student set age=21 where name='qq';
where 中可以使用or(或者)、and(并且)、not(非)、< (小于)、> (大于)、 >= (大于等于)、 <= (小于等于)、 != 即<>(不等于)等。

如果在sql语句中出现中文的话,最好在前面加 N ,例如:
Update tb_Student set name=N'囡囡' where age<=10;

删除表中数据:Delete from tb_Student 与Drop table tb_Student(删除表)的不同在于,delete只删除表中数据,表还在,但是,drop把整个表都删除。
delete也可加where语句来删除部分数据:delete from tb_Student where age=11;

查询结果可以将列名显示为其它,例如想让age列显示为年龄,name显示为姓名:select age as 年龄,name as 姓名 from tb_Student;

select 可以检索不与任何表关联的数据,例如:select getdate() 就可得到当前时间
select列名本身可以参与运算,select语句很灵活,可以随意嵌套,例如:select age+10 as 年龄,getdate() as 当前时间 from tb_Student (显示结果为第一列是student表中的所有age全都大了10岁显示,第二列是当前时间)

SQL聚合函数:最大值"max"、最小值"min" 、平均值"avg" 、和"sum" 、数量"count"
计算表中总数据条数:select count(*) from tb_Student;
找出表中最大年龄,最小年龄,平均年龄:select max(age),min(age),avg(age) from tb_Student;
计算表中所有年龄总和:select sum(age) from tb_Student;
聚合函数也可加where语句进行判断。

排序:order by 语句,放在where之后,位于select语句末尾,升序(ASC)降序(DESC),同时写两个,则前者优先进行排序:
select * from tb_Student order by age desc(按年龄降序排列),
select * from tb_Student order by age desc,grade asc;(相同年龄则按年级从低到高排序)

---------------------- Windows Phone 7手机开发、.Net培训、期待与您交流! ----------------------