欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

MSSQL经典语句

程序员文章站 2022-05-04 14:45:22
1.按姓氏笔画排序:select * from tablename order by customername collate chinese_prc_stroke_ci_...

1.按姓氏笔画排序:
select * from tablename order by customername collate chinese_prc_stroke_ci_as

2.数据库加密:
select encrypt('原始密码')
select pwdencrypt('原始密码')
select pwdcompare('原始密码','加密后密码') = 1--相同;否则不相同
encrypt('原始密码')
select pwdencrypt('原始密码')
select pwdcompare('原始密码','加密后密码') = 1--相同;否则不相同

3.取回表中字段:
declare @list varchar(1000),@sql nvarchar(1000)
select @list=@list+','+b.name from sysobjects a,syscolumns b where a.id=b.id and a.name='表a'
set @sql='select '+right(@list,len(@list)-1)+' from 表a'
exec (@sql)

4.查看硬盘分区:
exec master..xp_fixeddrives

5.比较a,b表是否相等:
if (select checksum_agg(binary_checksum(*)) from a)
    =
   (select checksum_agg(binary_checksum(*)) from b)
print '相等'
else
print '不相等'

6.杀掉所有的事件探察器进程:
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 '?'

7.记录搜索:
开头到n条记录

select top n * from
-------------------------------
n到m条记录(要有主索引id)
select top m-n * fromwhere id in (select top m id from 表) order by id  desc
----------------------------------
n到结尾记录
select top n * fromorder by id desc

8.如何修改数据库的名称:
sp_renamedb 'old_name', 'new_name' 

9:获取当前数据库中的所有用户表
select name from sysobjects where xtype='u' and status>=0

10:获取某一个表的所有字段
select name from syscolumns where id=object_id('表名')

11:查看与某一个表相关的视图、存储过程、函数
select a.* from sysobjects a, syscomments b where a.id = b.id and b.text like '%表名%'

12:查看当前数据库中所有存储过程
select name as 存储过程名称 from sysobjects where xtype='p'

13:查询用户创建的所有数据库
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

14:查询某一个表的字段和数据类型
select column_name,data_type from information_schema.columns
where table_name = '表名'

[n].[标题]:
select * from tablename order by customername 

[n].[标题]:
select * from tablename order by customername