请问用什么语句可以得到创建表时的表结构?
条件:要求是用sql语句搞定该问题,要求sql语句尽可能简练。
举例:假如数据库中有一个表Test(A,B,C)
要求结果:用sql语句得出Test的表结构,如下:
create table Test(A varchar(10),B varchar(10),C varchar(10))
------解决方案--------------------
Declare @TableName Varchar(50), @Columns Varchar(5000), @Sql Varchar(500), @Sql1 Varchar(500)
Declare Cur_Table Cursor for
Select Name From sysObjects Where Xtype = 'U' --And Name = @TableName
Order By Name
Open Cur_Table
Fetch Next From Cur_Table Into @TableName
While @@Fetch_Status = 0
Begin
Set @Sql = 'Create Table '+@TableName + ' (' + char(9)+char(10)
Set @Sql1 = ''
Declare Cur_Column Cursor For
Select Name
+ ' '+ Case xusertype When 167 Then type_name(xusertype)+'('+Cast(Length As Varchar(10))+')'
When 175 Then type_name(xusertype)+'('+Cast(Length As Varchar(10))+')' Else type_name(xusertype) End
+ ' '+Case when isnullable = 0 then 'Not Null' else '' end
+ ','
from SysColumns
where id = Object_ID(@TableName) and number = 0
order by colid
Open Cur_Column;
Fetch Next From Cur_Column Into @Columns;
While @@Fetch_Status = 0
Begin
Set @Sql1 = @Sql1 + @Columns +char(9)+char(10);
Fetch Next From Cur_Column Into @Columns;
End;
Close Cur_Column
Deallocate Cur_Column
Print @Sql + Left(Rtrim(@Sql1), Len(@Sql1)- 3)+')' +Char(9)+Char(10);
Fetch Next From Cur_Table Into @TableName
End
Close Cur_Table
Deallocate Cur_Table