SqlServer
1、sqlserver2008技术内幕:T-SQL语言基础练习
2、创建数据库,DB_ID判断数据库是否存在
IF DB_ID(‘testdb’) is null;
CREATE DATABASE testdb;
3、创建表,OBJECT_ID判断表是否存在
USE testdb;
IF OBJECT_ID(‘testdb.student’,‘U’) IS NOT NULL;
DROP TABLE testdb.student;
CREATE TABLE testdb.student
(
id int not null,
name varchar(30),
age int,
birthday datetime not null
)
4、添加主键约束,主键不能为null,表中只能有一个
ALTER TABLE testdb.student
ADD CONSTRAINTS PK_student_id
PRIMARY KEY (id);
5、添加唯一索引,唯一索引允许有null值。表中可以有多个唯一索引
ALTER TABLE testdb.student
ADD CONSTRAINTS UNQ_student_name
UNIQUE(name)
6、检查约束check,数据修改插入时,检查age>0
ALTER TABLE testdb.student
ADD CONSTRAINTS CHECK_student_age
CHECK(age>0)
7、添加默认约束
ALTER TABLE testdb.student
ADD CONSTRAINTS DEF_student_birthday
DEFAULT(CURRENT_TIMESTAMP) FOR birthday;
8、select语句查询顺序
1、FROM
2、WHERE
3、GROUP BY
4、HAVING
5、SELECT
6、ORDER BY
9、TOP子句
1、返回结果集中的前5行
SELECT TOP(5) id,name,age,birthday from testdb.student
ORDER BY name,age desc
2、按照前5%返回
SELECT TOP(5) PERCENT id,name,age,birthday from testdb.student
ORDER BY name,age desc
10、OVER子句,OVER用于为行定义一个窗口,它对一组值进行操作,不需要使用GROUP BY子句对数据进行分组,能够在同一行中同时返回基础行的列和聚合列。
11、CASE表达式
SELECT id, name, age, birthday
CASE id
WHEN id=1 then ‘aa’
ELSE ‘bb’
END
from testdb.student;
SELECT id, name, age, birthday
CASE
WHEN age>18 then ‘成年’
WHEN age< 18 then ‘未成年’
ELSE ‘UNOW’
from testdb.student;
12、CTE公用表达式
WITH test AS
(
select id, name, age, birthday
from testdb.student
WHERE age=18
)
select * from test
13、集合运算
并集
UNION ALL 结果集所有行,不去重
UNION DISTINCT 结果集去重
交集
INTERSECT DISTINCT 交集
差集
EXCEPTION
14、透视、逆透视及分组集
15、新增
insert into … select
INSERT EXECUTE
SELECT INTO …
16、删除
DELETE FROM …
TRUNCATE TABLE …
17、连接删除、连接修改、合并语句
18、OUTPUT输出语句,输出改变前和改变后的数据作为结果对比
19、事务
2、锁机制、锁的排查和解决
20、查询锁的状态,查询动态管理试图dmv
SELECT * FROM sys.dm_tran_locks;