Generate table structure with primary key based on table name

Source: Internet
Author: User


----------------------------------------
--Generate table structure with primary key based on table name
----------------------------------------
DECLARE @TableName varchar (255)
Set @TableName = ' Bao_color '--' company '
----------------------------------------
DECLARE @str varchar (max)
Set @str = ' '
Select @str = @str + char (9) + ', [' + Cols.name + '] '
+ Type.Name
+ (case if cols.xtype in (165,167,173,175,231,239)
Then ' (' + CONVERT (varchar (), Cols.prec) + ') '
When Cols.xtype in (106,108)
Then ' (' + convert (varchar), Cols.prec) + ', ' + CONVERT (varchar (), Cols.scale) + ') '
Else ' end)
+ Case If cols.isnullable = 1 Then ' else ' not NULL ' end
+ char (+) + char (10)
From syscolumns cols
INNER JOIN systypes type
On cols.xtype = Type.xtype and Cols.xtype = Type.xusertype
where cols.id = (select id from sysobjects where name = @TableName)

Declare @objectid int, @pkstr varchar (max)
Set @objectid =object_id (@TableName)
Set @pkstr = ' '
Select @pkstr = @pkstr + col_name (@objectid, colid) + ' ASC, '
From sysobjects as O
Inner Join sysindexes as I on I.name=o.name
Inner Join Sysindexkeys as K on K.indid=i.indid
Where o.xtype = ' PK ' and [email protected] and [email protected]

Set @pkstr = ISNULL (@pkstr, ")

Set @pkstr = case when @pkstr = "then" Else SUBSTRING (@pkstr, 1, LEN (@pkstr)-1) End


Set @str = ' CREATE TABLE dbo. ' + @TableName + ' (' + char (+) + char (+) + char (9)
+substring (@str, 3,len (@str)-1) + char (+) + char (10)
+ Case @pkstr = "then"
Else ' PRIMARY KEY CLUSTERED (' + char (+) + char (10)
+ char (9) + + @pkstr + char (+) + char (10)
+ char (9) + + ') on [PRIMARY] ' + char (+) + char (10)
End
+ ') '

Print @str





Generate table structure with primary key based on table name

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.