1
系统视图,系统表,系统存储过程的使用
获取数据库中用户表信息
1
、获取特定库中所有用户表信息
select
*
from
sys
.
tables
select
*
from
sys
.
objects
where
type
=
'U'
--
用户表
第二条语句中当
type='S'
时是系统表
2
、获取表的字段信息
select
*
from
sys
.
columns
where
object_id
=
object_id
(
'
表名
'
)
select
*
from
syscolumns
where
id
=
OBJECT_ID
(
'
表名
'
)
3
、获取当前库中表的字段及类型信息
(
1
)
select
'
字段名
'
=
a
.
name
,
'
类型名
'
=
b
.
name
,
'
字段长度
'
=
a
.
max_length
,
'
参数顺序
'
=
a
.
column_id
from
sys
.
columns
a
left
join
sys
.
types
b
on
a
.
user_type_id
=
b
.
user_type_id
where
object_id
=
object_id
(
'
表名
'
)
syscolumns
与
sys.columns
表用法类似。
获取索引或主键信息
1
、
获取对象及对应的索引的信息
select
'
对象名
'
=
A
.
name
,
'
对象类型
'
=
a
.
type
,
'
索引名
'
=
B
.
name
,
'
索引类型
'
=
case
b
.
type
when
1
then
'
聚集索引
'
when
2
then
'
非聚集索引
'
when
3
then
'xml
索引
'
else
'
空间索引
'
end
,
'
主键否
'
=
case
when
b
.
is_primary_key
=
1
then
'
主键
'
else
''
end
FROM
sys
.
objects
A
JOIN
sys
.
indexes
B
ON
A
.
object_id
=
B
.
object_id
WHERE
A
.
type
=
'U'
AND
B
.
name
IS
NOT
NULL
order
by
a
.
name
2
、
获取表的主键及对应的字段
(
1
)
select
'
表名
'
=
d
.
name
,
'
主键名
'
=
a
.
name
,
'
字段名
'
=
c
.
name
from
sys
.
indexes
a
join
sys
.
index_columns
b
on
a
.
object_id
=
b
.
object_id
and
a
.
index_id
=
b
.
index_id
join
sys
.
columns
c
on
a
.
object_id
=
c
.
object_id
and
c
.
column_id
=
b
.
column_id
join
sys
.
objects
d
on
d
.
object_id
=
c
.
object_id
where
a
.
is_primary_key
=
1
(
2
)
SELECT
'
表名
'
=
OBJECT_NAME
(
b
.
parent_obj
),
'
主键名
'
=
c
.
name
,
'
字段名
'
=
a
.
name