SQL Server 没有提供函数或存储过程直接查看建表语句(?),当然它的DBMS客户端提供了这个功能,但只为了这点小事就安装那个大玩意?…还是自己写一个更快。
完整代码
createProcedure sp_helptable ( @tablevarchar(100) ) -- exec sp_helptable tablename -- 增加获取注释信息(感谢 袁罗) AS Begin declare@sqltable(s varchar(1000), id intidentity) -- 创建语句 insertinto@sql(s) values ('create table ['+@table+'] (')
--获取注释 SELECT A.name AS table_name, B.name AS column_name, C.value AS column_description into #columnsproperties FROM sys.tables A INNERJOIN sys.columns B ON B.object_id = A.object_id LEFTJOIN sys.extended_properties C ON C.major_id = B.object_id AND C.minor_id = B.column_id WHERE A.name =@table
-- 获取列的列表,拼接语句 insertinto@sql(s) select ' ['+a.column_name+'] '+ data_type +coalesce('('+cast(character_maximum_length asvarchar)+')','') +' '+ casewhenexists ( select id from syscolumns where object_name(id)=@table and name=a.column_name and columnproperty(id,name,'IsIdentity') =1 ) then 'IDENTITY('+ cast(ident_seed(@table) asvarchar) +','+ cast(ident_incr(@table) asvarchar) +')' else'' end+' '+ ( casewhen IS_NULLABLE ='NO'then'NOT 'else''end ) +'NULL '+ coalesce('DEFAULT '+COLUMN_DEFAULT,'') +casewhen isnull(convert(varchar,b.column_description),'')<>''then'/**'+isnull(convert(varchar,b.column_description),'')+'**/,' else','end from INFORMATION_SCHEMA.COLUMNS a leftjoin #columnsproperties b onconvert(varchar,a.column_name)=convert(varchar,b.column_name) where a.table_name =@table orderby ordinal_position -- 主键 declare@pknamevarchar(100) select@pkname= constraint_name from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where table_name =@tableand constraint_type='PRIMARY KEY' if ( @pknameisnotnull ) begin insertinto@sql(s) values(' PRIMARY KEY (') insertinto@sql(s) select' ['+COLUMN_NAME+'],'from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where constraint_name =@pkname orderby ordinal_position -- 去除尾部多余的字符 update@sqlset s=left(s,len(s)-1) where id=@@identity insertinto@sql(s) values (' )') end elsebegin -- 去除尾部多余的字符 update@sqlset s=left(s,len(s)-1) where id=@@identity end -- 继续拼接 insertinto@sql(s) values( ')' ) -- 输出结果 select s from@sqlorderby id END