sql server 常用语句持续更新
sql 常用语句用法
--子查询用法
select s#,sname from student where s# in(select s# from sc )
--in查询用法(in:满足,not in :不满足)
select s#,sname from student where s# not in(1,2)
--UNION 运算符
UNION 运算符通过组合其他两个结果表(例如 TABLE1 和 TABLE2)并消去表中任何重复行而派生出一个结果表。当 ALL 随 UNION 一起使用时(即 UNION ALL),不消除重复行。两种情况下,派生表的每一行不是来自 TABLE1 就是来自 TABLE2。
select s# from student UNION all
select s# from sc
--EXCEPT 运算符
EXCEPT 运算符通过包括所有在 TABLE1 中但不在 TABLE2 中的行并消除所有重复行而派生出一个结果表。当 ALL 随 EXCEPT 一起使用时 (EXCEPT ALL),不消除重复行。
select s# from student EXCEPT
select s# from sc
--INTERSECT 运算符
INTERSECT 运算符通过只包括 TABLE1 和 TABLE2 中都有的行并消除所有重复行而派生出一个结果表。当 ALL 随 INTERSECT 一起使用时 (INTERSECT ALL),不消除重复行。 注:使用运算词的几个查询结果行必须是一致的。
select s# from student INTERSECT
select s# from sc
--左连接查询 LEFT JOIN 或者 LEFT outer JOIN
结果集几包括连接表的匹配行,也包括左连接表的所有行
select a.s#,a.sname,b.s#,b.score from student as a LEFT JOIN sc as b on a.s#=b.s#
--右连接查询 right outer join
结果集既包括连接表的匹配连接行,也包括右连接表的所有行。
select a.s#,a.sname,b.s#,b.score from student as a right outer join sc as b on a.s#=b.s#
--全连接查询 full outer join
不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录
select a.s#,a.sname,b.s#,b.score from student as a full outer join sc as b on a.s#=b.s#
--在线视图查询(表名1:a )
select * from (SELECT a,b,c FROM a) T where t.a > 1;
--两张关联表,删除主表中已经在副表中没有的信息
EXISTS 运算符用于判断查询子句是否有记录
delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 )
--四表联查:
select * from a left inner join b on a.a=b.b right inner join c on a.a=c.c inner join d on a.a=d.d where .....
--查询前5条数据top
select top 5 * from sc
--查询随机5条数据
随机函数:newid()
select top 5 * from sc order by newid()
--查询数据库所有表名
select name from sysobjects where type='U'
--查询第5条到第15条数据
select top 5 * from (select top 15 * from table order by id asc) table_别名 order by id desc
sql server 数据库操作
--更改为简单模式
USE [master]
GO
ALTER DATABASE JKDB_BS SET RECOVERY SIMPLE WITH NO_WAIT
GO
ALTER DATABASE JKDB_BS SET RECOVERY SIMPLE
GO
--清理日志文件
USE JKDB_BS
GO
DBCC SHRINKFILE (N'JKDB_BS_Log' , 11, TRUNCATEONLY)
GO
--还原为完全模式
USE [master]
GO
ALTER DATABASE JKDB_BS SET RECOVERY FULL WITH NO_WAIT
GO
ALTER DATABASE JKDB_BS SET RECOVERY FULL
GO
--当前数据库,数据文件占用与剩余空间
SELECT DB_NAME() AS JKDB_BS,
name AS FileName,
size/128.0 AS CurrentSizeMB,
size/128.0 - CAST(FILEPROPERTY(name, 'SpaceUsed') AS INT)/128.0 AS FreeSpaceMB
FROM sys.database_files;
--查询各个表空间占用情况
SELECT a.name, b.rows
FROM sys.sysobjects AS a INNER JOIN
sys.sysindexes AS b ON a.id = b.id
WHERE (b.indid IN (0, 1)) AND (a.type = 'u')
ORDER BY b.rows DESC