34,588
社区成员
发帖
与我相关
我的任务
分享
/*
-- 本帖想收集汇总一些 Microsoft SQL Server 中有关数据库与表的相关信息查询语句。
-- 查询语句中一般给出两种查询方法,
-- A方法访问系统表,适应于SQL 2000/2005/2008/2008 R2,但是在微软的联机帮助中特意说明这些系统表
-- 在后续版本的 Microsoft SQL Server 将删除该功能。请避免在新的开发工作中使用该功能。
--
-- B方法访问系统视图,为微软推荐使用方法,对于今后新版本 SQL Server 兼容性比较好。
-- 两种方法存在细微差别,下面的网址给出了系统表与函数以及系统视图与函数之间的映射。
-- http://technet.microsoft.com/zh-cn/library/ms187997.aspx
*/
--在这先抛砖引玉一下,大家多提供一些常用经典语句!
--1、查询数据库中有哪些表名
select name, id FROM sysobjects o where o.type = 'U' -- A
select name, [object_id] FROM sys.objects o where o.type = 'U'; -- B
--其中where条件还可按下面改:
A:type = 'K' B:type = 'PK' --主键
type = 'P' -- 存储过程
type = 'S' -- 系统表
type = 'V' -- 视图
--2、查询表的字段名称和数据类型
--旧方法
select 'TableName' as TableName
,c.name as ColumnName
,t.name as DataType
from syscolumns c
join systypes t
on c.xtype = t.xtype and c.id=object_id( N'TableName');
--新方法
select 'TableName' as TableName
, c.name as ColumnName
, t.name as DataType
from sys.COLUMNS c
join sys.types t
on c.system_type_id = t.system_type_id
and c.object_id=object_id( N'TableName');
--也可通过 information_schema.columns 访问
--3、查询表中的主键
select b.name as tableName, a.name as PK_Name
FROM sysobjects a
join sysobjects b
on a.type = 'K' and b.type = 'U'
and a.parent_obj = b.id
and b.name = 'TableName'
select b.name as tableName, a.name as PK_Name
FROM sys.objects a
join sys.objects b
on a.type = 'PK' and b.type = 'U'
and a.parent_object_id = b.object_id
and b.name = 'TableName'
--4、查询表中的索引
EXEC sp_helpindex N'tableName'