日期:2014-05-19  浏览次数:20595 次

如何比较2个数据库中表结构?
比较2个数据库中某个相同数据名称表的结构;比较相关的字段的差异
添加,减少,字段变化
用SQL语句;
好像master里有
                      求教!!!!

------解决方案--------------------
比较:

select name from syscolumns
where id=object_id( 'tblname1 ')

select name from syscolumns
where id=object_id( 'tblname2 ')


------解决方案--------------------
--以前收集的 但不记得是那位大侠写的了
/*--比较两个数据库的表结构差异

--*/
/*--调用示例

exec p_comparestructure 'xzkh_model ', 'xzkh_new '
--*/

if exists (select * from dbo.sysobjects where id = object_id(N '[dbo].[p_comparestructure] ') and OBJECTPROPERTY(id, N 'IsProcedure ') = 1)
drop procedure [dbo].[p_comparestructure]
GO

create proc p_comparestructure
@dbname1 varchar(250), --要比较的数据库名1
@dbname2 varchar(250) --要比较的数据库名2
as
create table #tb1(表名1 varchar(250),字段名 varchar(250),序号 int,标识 bit,主键 bit,类型 varchar(250),
占用字节数 int,长度 int,小数位数 int,允许空 bit,默认值 varchar(500),字段说明 varchar(500))

create table #tb2(表名2 varchar(250),字段名 varchar(250),序号 int,标识 bit,主键 bit,类型 varchar(250),
占用字节数 int,长度 int,小数位数 int,允许空 bit,默认值 varchar(500),字段说明 varchar(500))

--得到数据库1的结构
exec( 'insert into #tb1 SELECT
表名=d.name,字段名=a.name,序号=a.colid,
标识=case when a.status=0x80 then 1 else 0 end,
主键=case when exists(SELECT 1 FROM '+@dbname1+ '..sysobjects where xtype= ' 'PK ' ' and name in (
SELECT name FROM '+@dbname1+ '..sysindexes WHERE indid in(
SELECT indid FROM '+@dbname1+ '..sysindexkeys WHERE id = a.id AND colid=a.colid
))) then 1 else 0 end,
类型=b.name, 占用字节数=a.length,长度=a.prec,小数位数=a.scale, 允许空=a.isnullable,
默认值=isnull(e.text, ' ' ' ' ' '),字段说明=isnull(g.[value], ' ' ' ' ' ')
FROM '+@dbname1+ '..syscolumns a
left join '+@dbname1+ '..systypes b on a.xtype=b.xusertype
inner join '+@dbname1+ '..sysobjects d on a.id=d.id and d.xtype= ' 'U ' ' and d.name <> ' 'dtproperties ' '
left join '+@dbname1+ '..syscomments e on a.cdefault=e.id
left join '+@dbname1+ '..sysproperties g on a.id=g.id and a.colid=g.smallid
order by a.id,a.colorder ')

--得到数据库2的结构
exec( 'insert into #tb2 SELECT
表名=d.name,字段名=a.name,序号=a.colid,
标识=case when a.status=0x80 then 1 else 0 end,
主键=case when exists(SELECT 1 FROM '+@dbname2+ '..sysobjects where xtype= ' 'PK ' ' and name in (
SELECT name FROM '+@dbname2+ '..sysindexes WHERE indid in(
SELECT indid FROM '+@dbname2+ '..sysindexkeys WHERE id = a.id AND colid=a.colid
))) then 1 else 0 end,
类型=b.name, 占用字节数=a.length,长度=a.prec,小数位数=a.scale, 允许空=a.isnullable,
默认值=isnull(e.text, ' ' ' ' ' '),字段说明=isnull(g.[value], ' ' ' ' ' ')
FROM '+@dbname2+ '..syscolumns a
left join '+@dbname2+ '..systypes b on a.xtype=b.xusertype
inner join '+@dbname2+ '..sysobjects d on a.id=d.id and d.xtype= ' 'U ' ' and d.name <> ' 'dtproperties ' '
left join '+@dbname2+ '..syscomments e on a.cdefault=e.id
left join '+@dbname2+ '..sysproperties g on a.id=g.id and a.colid=g.smallid
order by a.id,a.colorder ')
--and not exists(select 1 from #tb2 where 表名2=a.表名1)
select 比较结果=case when a.表名1 is null and b.序号=1 then '库1缺少表: