收集一些数据库信息查询语句?

tjs_125 2012-04-25 11:17:33
我先抛砖引玉一下,大家多提供一些常用经典语句!
/*
-- 本帖想收集汇总一些 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'
...全文
123 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
叶子 2012-04-26
  • 打赏
  • 举报
回复
  • 打赏
  • 举报
回复
精华贴中有,已经有人整理过了,不要再重复整理了。
唐诗三百首 2012-04-25
  • 打赏
  • 举报
回复
怎样才算"经典"?
-狙击手- 2012-04-25
  • 打赏
  • 举报
回复
select *
from ta a
where exists(select 1 from tb where a.a1 = a1 and a.a2 = a2 and a.a3 = a3)

34,588

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧