KeepHoist

一、首先要了解Sqlserver 中系统表对象及表结构查询的函数:sysobjects、syscolumns以及函数object_id

     

 1. sysobjects ——  系统对象表。 保存当前数据库的对象,如约束、默认值、日志、规则、存储过程等

注:重要字段需要解释的是 xtype,他的数据字段内容分别表示为:

C = CHECK 约束

D = 默认值或 DEFAULT 约束

F = FOREIGN KEY 约束

FN = 标量函数

IF = 内嵌表函数

K = PRIMARY KEY 或 UNIQUE 约束

L = 日志

P = 存储过程

R = 规则

RF = 复制筛选存储过程

S = 系统表

TF = 表函数

TR = 触发器

U = 用户表

V = 视图

X = 扩展存储过程

 

2. sysolumns —— 当前数据库的所有表里面创建的字段都保留在里面

注:SQL中的sysobjects 的id与syscolumns 的id 存在主键关系,即 syscolumns 中的id字段是 sysobjects 表的主键对应值(查询时: select name from syscolumns where id=(select id from sysobjects where name=\'表名\')

 

3. object_id(\'表名\') —— 函数表示直接取表对象的ID值。此方法返回数据库对象标识号

注:查询时:  select name from syscolumns where  id =object_id(\'TB\')  等同于上述查询

 

二、比较同一数据库中两个表的对应字段的差异(当两个表结构一样时,查询表对应的字段是否一致)

select * from (
select name
from syscolumns
where id=(
select id from sysobjects
where name=\'表名1\')
) T1
FULL OUTER JOIN(
select name from syscolumns
where id=(
select id from sysobjects
where name=\'表名2\')
) T2 on T1.name=T2.name
where T1.name is null or T2.name is null

 

三、比较在不同数据库中两个表的对应字段的差异(当两个表结构一样时,查询表对应的字段是否一致)

select * from (
select name
from gxjmxy.dbo.syscolumns
where id=(
select id from gxjmxy.dbo.sysobjects
where name=\'TB1\')
) T1 FULL OUTER JOIN(
select name from Test.dbo.syscolumns
where id=(
select id from Test.dbo.sysobjects
where name=\'TB\'
)
) T2 on T1.name=T2.name
where T1.name is null or T2.name is null

 

分类:

技术点:

相关文章:

  • 2021-09-20
  • 2022-12-23
  • 2021-11-29
  • 2022-12-23
  • 2021-11-30
  • 2022-12-23
  • 2022-12-23
  • 2021-07-20
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-08-03
  • 2022-02-07
  • 2022-02-17
  • 2021-12-15
  • 2021-08-18
相关资源
相似解决方案