SQL Server中查询数据库及表的信息语句

/*
-- 本文件主要是汇总了 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
select column_name
,data_type --系统提供的数据类型。
,IS_NULLABLE --列的为空性。如果列允许 NULL,则该列将返回 YES。否则,返回 NO。
,COLUMN_DEFAULT --列的默认值。没有,返回 NULL。
,CHARACTER_MAXIMUM_LENGTH --二进制数据、字符数据或文本和图像数据的最大长度(字符)。对于 xml 和大值类型数据,为 -1.否则,返回 NULL。
,CHARACTER_OCTET_LENGTH --二进制数据、字符数据或文本和图像数据的最大长度(字节)。对于 xml 和大值类型数据,为 -1.否则,返回 NULL。
,NUMERIC_PRECISION --近似数字数据、精确数字数据、整数数据或货币数据的精度。否则,返回 NULL。
,NUMERIC_PRECISION_RADIX --近似数字数据、精确数字数据、整数数据或货币数据的精度基数。否则,返回 NULL。
,NUMERIC_SCALE --近似数字数据、精确数字数据、整数数据或货币数据的小数位数。否则,返回 NULL。
from information_schema.columns
where table_name = 'TableName'; --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'
上一篇:python 获取秒级时间间隔


下一篇:Sql Server中查询今天、昨天、本周、上周、本月、上月数据