首页 > 代码库 > SQL语句大全
SQL语句大全
1.随机取3条记录
select top 3 * from tablename newid()
2.随机选记录
select newid().
3.删除重复记录
1) delete from tablename where id not in (select max(id) from tablename group by col1,col2,...)
2)select distinct * into temp fromtablename
delete fromtablename
insert into tablename select * from temp
4.列出数据库里所有的表名
select name from sysobjects where type=‘U‘
5.列出表里的所有的列名
select name from syscolumns where id=object_id(‘TableName‘)
6.选择从10到15的记录
select top 5 * from(select top 15 * from tablename order by id asc) table_别名 order by id desc
7.压缩数据库
dbcc shrinkdatabase(dbname)
8.按姓氏笔画排序
Select * From TableName Order By CustomerName Collate Chinese_PRC_Stroke_ci_as //从少到多
9.数据库加密
select encrypt(‘原始密码‘)
select pwdencrypt(‘原始密码‘)
select pwdcompare(‘原始密码‘,‘加密后密码‘) = 1--相同;否则不相同 encrypt(‘原始密码‘)
select pwdencrypt(‘原始密码‘)
select pwdcompare(‘原始密码‘,‘加密后密码‘) = 1--相同;否则不相同
10.查看硬盘分区
EXEC master..xp_fixeddrives
11.比较两表是否相等
if(select checksum_agg(binary_checksum(*))from A)=(select checksum_agg(binary_checksum(*))from B)
print ‘相等‘
else
print ‘不相等‘
12.杀掉所有的事件探察器进程:
DECLARE hcforeach CURSOR GLOBAL FOR SELECT ‘kill ‘+RTRIM(spid) FROM master.dbo.sysprocesses
WHERE program_name IN(‘SQL profiler‘,N‘SQL 事件探查器‘)
EXEC sp_msforeach_worker ‘?‘
13.获取当前数据库中的所有用户表
select Name from sysobjects where xtype=‘u‘ and status>=0
14.查看与某一个表相关的视图、存储过程、函数
select a.* from sysobjects a, syscomments b where a.id = b.id and b.text like ‘%表名%‘
15.查看当前数据库中所有存储过程
select name as 存储过程名称 from sysobjects where xtype=‘P‘
16.查询用户创建的所有数据库
select * from master..sysdatabases D where sid not in(select sid from master..syslogins where name=‘sa‘)
或者
select dbid, name AS DB_NAME from master..sysdatabases where sid <> 0x01
17.创建数据库
create database dbname
18.删除数据库
drop database dbname
19.备份sql server
--- 创建 备份数据的 device
USE master
EXEC sp_addumpdevice ‘disk‘, ‘testBack‘, ‘c:\mssql7backup\MyNwind_1.dat‘
--- 开始 备份
BACKUP DATABASE pubs TO testBack