常用方法(系统表操作)

1. 如何取得一个数据表的所有列名
方法如下:先从sysobjects系统表中取得数据表的systemid,然后再syscolumns表中取得该数据表的所有列名。
SQL语句如下:
Declare @objid int,@objname char(40)
set @objname = 'ColumnToRow'
--第1种方法
select @objid = id from sysobjects where id = object_id(@objname)
select 'Column_name' = name from syscolumns where id = @objid order by colid
--或也可以写成
select name as 'Column_name' from syscolumns where id = @objid order by colid
--第2种方法:
Select name as 'Column_Name' from SysColumns where id = object_id(@objname) Order by colid

2. 通过SQL语句来更改用户的密码
修改别人的,需要sysadmin role 
Exec Sp_password '原始密码','更改后密码','账号'
Exec sp_password null,ok,sa

3. 怎么判断出一个表的哪些字段不允许为空?
Declare @objname Varchar(50)
set @objname = 'ColumnToRow'
Select Column_Name from information_schema.Columns where is_nullable = 'No' and Table_Name = @objname

4. 如何在数据库里找到含有相同字段的表?
a. 查已知列名的情况
Select a.name as Columnname,b.name as tablename from SysColumns a inner join sysobjects b on a.id = b.id
and b.type = 'U' and a.name = '您要查找的字段名'
b. 未知列名查所有在不同表出现过的列名
Select s.name as tablename,s1.name as columnname from SysColumns s1,Sysobjects s 
Where s1.id = s.id and s.Type = 'U' and Exists (Select 1 from syscolumns s2 where s1.name = s2.name and s1.id <> s2.id)

5.查询第N行数据
假设id是主键: 
select * 
from (select top N * from 表) aa 
where not exists(select 1 from (select top N-1 * from 表) bb where aa.id=bb.id)

你可能感兴趣的:(常用方法)