分类: 数据库开发技术
2006-11-29 17:31:18
/*☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆
描述: 得到数据库所有表的create语句
作者: magicangel
制作日期: 2004-06-04
输入: 无
输出: 无
功能说明: 效果与在EM里生成表脚本的功能一样
☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆*/
--exec up_getTableStruct
if exists (select * from sysobjects where objectproperty(object_id('up_getTableStruct'), 'IsProcedure') = 1)
drop procedure up_getTableStruct
go
create procedure up_getTableStruct
as
begin
set nocount on
declare @i_objectId int, -- 对象id
@i_indId smallint, -- 索引id
@v_pkInfo varchar(100), -- 主键信息
@v_clusteredInfo varchar(20), -- clustered信息
@v_pkCol varchar(100), -- 主键字段
@v_key varchar(50),
@i_i smallint
create table #temp1
(
i_id int identity,
v_desc varchar(200)
)
declare @v_tableName varchar(256)
declare getTableStruct_cur cursor for select name from sysobjects where xtype='u'
open getTableStruct_cur
fetch next from getTableStruct_cur into @v_tableName
while @@fetch_status=0
begin
set @i_objectId = object_id(@v_tableName)
insert into #temp1(v_desc)
values('create table '+'['+@v_tableName+']'+'(') --
insert into #temp1(v_desc) -- 将表的字段信息存入临时表
select a.name+space(4)+b.name+
case when b.xtype in (167,175,231,239) then '('+cast(a.length as varchar)+')'
when b.xtype in (106,108) then '('+cast(a.xprec as varchar)+','+cast(a.xscale as varchar)+')'
else '' end+space(4)+
case when (a.colstat & 1 = 1) then 'identity('+cast(ident_seed(@v_tableName) as varchar)+',' +
cast(ident_incr(@v_tableName) as varchar)+')' else '' end +space(4)+
case a.isnullable when 0 then 'not null' else 'null' end+'|'
from syscolumns a,systypes b
where a.id = @i_objectId and a.xtype = b.xusertype
order by a.colid
if exists(select 1 from sysobjects where parent_obj = @i_objectId and xtype = 'PK') -- 如果存在主键
begin
select @v_pkInfo = b.name,@i_indId = indid, -- 得到主键名,id及是否clustered信息
@v_clusteredInfo = (case when (a.status & 16)=16 then 'clustered' else 'nonclustered' end )
from sysindexes a,sysobjects b
where a.id = b.parent_obj and a.name = b.name and b.xtype = 'PK' and b.parent_obj = @i_objectId
select @v_pkCol = index_col(@v_tableName, @i_indId, 1), @i_i = 2 -- 得到主键的第1个字段名
select @v_key = index_col(@v_tableName, @i_indId, @i_i) -- 得到主键的第2个字段名
while (@v_key is not null)
begin
select @v_pkCol = @v_pkCol + ',' + @v_key, @i_i = @i_i + 1
select @v_key = index_col(@v_tableName, @i_indId, @i_i) -- 得到主键的第@i_i个字段名
end -- 组合成主键信息
set @v_pkInfo = 'constraint primary key
insert into #temp1(v_desc) values(@v_pkInfo) -- 将主键信息插入临时表
end
else
begin
select @i_i = count(1) from #temp1
-- 如果没有主键,那么将最后一笔纪录的'|'去掉
update #temp1 set v_desc = replace(v_desc,'|','') where i_id = @i_i
end
insert into #temp1(v_desc) values(')') --
update #temp1 set v_desc = replace(v_desc,'|',',')
fetch next from getTableStruct_cur into @v_tableName
end
select v_desc from #temp1 order by i_id
drop table #temp1
close getTableStruct_cur
deallocate getTableStruct_cur
set nocount off
end