生成建表脚本up_CreateTable

已经很久没用使用这个脚本了,今天用到,并做修改,增加了生成扩展属性功能。

Go
if object_ID(‘[up_CreateTable]‘) is not null
	Drop Procedure [up_CreateTable]
Go
/* 生成建表脚本(V4.0)  Andy 2017-3-28 */
Create Proc up_CreateTable
(
    @objectList nvarchar(max)=null
)
as
--With ENCRYPTION

/*  参数说明:
    @objectList 对象列表,对象之间使用","隔开

    存储过程生成的建表脚本,包含Column,Constraint,Index,extended_properties

	Modify: andy 2017-3-28 增加了扩展属性
*/
Set Nocount On
    Declare @sql nvarchar(max),
            @objectid int,
            @id int,
            @Rowcount int,
            @ObjectName sysname,
            @Enter nvarchar(2),
            @Tab nvarchar(2)

    Select     @Enter=Char(13)+Char(10),
            @Tab=Char(9)    

    Declare @Tmp Table(name sysname)

    If @objectList>‘‘
    Begin
        Set @sql=‘Select N‘‘‘+Replace(@objectList,‘,‘,‘‘‘ Union All Select N‘‘‘)+‘‘‘‘
        Insert Into @Tmp (name) Exec(@sql)

        Set @sql=null
        Select @sql=Isnull(@sql+‘,‘,‘‘)+name
            From @Tmp As a
            Where Not Exists(Select 1 From sys.objects Where type=‘U‘ And name=a.name)

        If @sql>‘‘
        Begin
            Set @sql=‘发现无效的表名: ‘[email protected]
           Raiserror (50001,-1,-1, @sql)
            Return(1)

        End
    End

    If object_id(‘tempdb..#Objects‘) Is Not Null
        Drop Table #Objects

    If object_id(‘tempdb..#Columns‘) Is Not Null
        Drop Table #Columns    

    Create Table #Objects(id int Identity(1,1) Primary Key,object_id int,name sysname)

    ;With t As
    (
    Select Object_id,Convert(int,0) As LevelNo,name As object_name
            From sys.objects a
            Where Type=‘U‘ And is_ms_shipped=0 And Not Exists(Select 1 From sys.foreign_keys Where referenced_object_id=a.object_id)
    Union All
    Select a.referenced_object_id As Object_id,b.LevelNo+1 As LevelNo,c.name As object_name
        From sys.foreign_keys a
            Inner Join t b On b.object_id=a.parent_object_id
            Inner Join sys.objects c On c.object_id=a.referenced_object_id And c.is_ms_shipped=0
		where a.referenced_object_id<>a.parent_object_id
    )
    Insert Into #Objects(object_id,name)
        Select a.object_id,object_name
            From t a
            Where    Not Exists(Select 1 From t Where object_id=a.object_id And LevelNo>a.LevelNo) And
                    Not Exists(Select 1 From sys.extended_properties Where major_id=a.object_id And minor_id=0 And class=1 And Name=N‘microsoft_database_tools_support‘)
                    And (Exists(Select 1 From @Tmp Where name=a.object_name) Or Not Exists(Select 1 From @Tmp))
            Group By object_id,object_name,LevelNo
            Order By LevelNo Desc

    Set @[email protected]@Rowcount
    If @Rowcount=0
    Begin
       -- Raiserror 50001 N‘没有可以生产脚本的表!‘
		Raiserror (50001,-1,-1, N‘没有可以生产脚本的表!‘)
        Return(1)
    End

    --Column
    Select    a.object_id,
            a.column_id As Seq,
            Cast(1 As tinyint) As DefinitionType,
            Quotename(a.name)+Char(32)+ c.name +
            Case
                When a.user_type_id In (231,239) Then ‘(‘+Case a.max_length When -1 Then ‘Max‘ Else Rtrim(a.max_length/2) End +‘)‘
                When a.user_type_id In (62,165,167,173,175) Then ‘(‘+Case a.max_length When -1 Then ‘Max‘ Else Rtrim(a.max_length) End+‘)‘
                When a.user_type_id In (106,108) Then ‘(‘+Rtrim(a.[precision])+‘,‘+Rtrim(a.scale)+‘)‘
                Else ‘‘
            End
            + Char(32)+
            Case a.is_rowguidcol When 1 Then ‘Rowguidcol ‘ Else ‘‘ End +
            Case a.is_identity When 1 Then ‘Identity(‘+Cast(d.seed_value As nvarchar(10))+‘,‘+Cast(d.increment_value As nvarchar(10))+‘) ‘ Else ‘‘ End+
            Case a.is_nullable When 1 Then ‘Null ‘ Else ‘Not Null ‘ End+
            Isnull(‘Constraint ‘+Quotename(e.name)+‘ Default(‘+e.definition+‘)‘,‘‘) As definition

            Into #Columns
        From sys.columns As a
            Inner Join #Objects As b On b.object_id=a.object_id
            Inner Join sys.types As c On c.user_type_id=a.user_type_id
            Left Outer Join sys.identity_columns As d On d.object_id=a.object_id And d.column_id=a.column_id And a.is_identity=1
            Left Outer Join sys.Default_constraints As e On e.object_id=a.default_object_id And e.parent_column_id=a.column_id

        Create Nonclustered Index IX_#Columns_object_id On #Columns(object_id Asc)

        --Constraint
        Insert Into #Columns

        Select    a.parent_object_id As object_id,
                Row_number() Over(Partition By a.parent_object_id Order By Case a.type When ‘PK‘ Then 1 When ‘C‘ Then 2 Else 3 End)As Seq,
                2 As DefinitionType,
                ‘Alter Table ‘+Quotename(object_name(a.parent_object_id)) +‘ Add Constraint ‘+Quotename(a.name)+
                Case a.type
                    When ‘PK‘ Then ‘ Primary Key ‘+Case When Exists(Select 1 From sys.indexes Where object_id=a.parent_object_id And is_primary_key=1 And type=1) Then N‘Clustered ‘ Else N‘Nonclustered ‘ End+
                                                ‘(‘+Stuff((Select ‘,‘+Quotename(c1.Name)+Case a1.is_descending_key When 1 Then ‘ Desc‘ Else ‘ Asc‘ End
                                                        From sys.index_columns As a1
                                                            Inner Join sys.indexes As b1 On b1.object_id=a1.object_id And b1.index_id=a1.index_id And b1.is_primary_key=1
                                                            Inner Join sys.columns As c1 On c1.object_id=a1.object_id And c1.column_id=a1.column_id
                                                        Where a1.object_id=a.parent_object_id
                                                        For Xml Path(‘‘)
                                                    ),1,1,‘‘)+
                                                ‘)‘
                    When ‘F‘ Then ‘ Foreign Key (‘+Stuff((Select ‘,‘+Quotename(b1.Name)
                                                        From sys.foreign_key_columns As a1
                                                            Inner Join sys.columns As b1 On b1.object_id=a1.parent_object_id And b1.column_id=a1.parent_column_id
                                                        Where a1.constraint_object_id=a.object_id
                                                        Order By a1.constraint_column_id
                                                        For Xml Path(‘‘)
                                                    ),1,1,‘‘)+
                                                ‘) References ‘+(Select Quotename(object_name(referenced_object_id)) From  sys.foreign_keys Where object_id=a.object_id)+
                                                ‘ (‘
                                                    +Stuff((Select ‘,‘+Quotename(b1.Name)
                                                        From sys.foreign_key_columns As a1
                                                            Inner Join sys.columns As b1 On b1.object_id=a1.referenced_object_id And b1.column_id=a1.referenced_column_id
                                                        Where a1.constraint_object_id=a.object_id
                                                        Order By a1.constraint_column_id
                                                        For Xml Path(‘‘)
                                                    ),1,1,‘‘)+
                                                ‘)‘
                    When ‘UQ‘ Then ‘ Unique‘+(Select Case a1.type When 1 Then ‘ Clustered‘ Else ‘ Nonclustered‘ End
                                                    From sys.indexes As a1
                                                    Where a1.object_id=a.parent_object_id
                                                                And Exists(Select 1 From sys.key_constraints Where object_id=a.object_id And parent_object_id=a1.object_id And unique_index_id=a1.index_id)
                                               )+
                                                ‘(‘+Stuff((Select ‘,‘+Quotename(c1.Name)+Case a1.is_descending_key When 1 Then ‘ Desc‘ Else ‘ Asc‘ End
                                                        From sys.index_columns As a1
                                                            Inner Join sys.indexes As b1 On b1.object_id=a1.object_id And b1.index_id=a1.index_id And b1.is_unique_constraint=1
                                                            Inner Join sys.columns As c1 On c1.object_id=a1.object_id And c1.column_id=a1.column_id
                                                        Where a1.object_id=a.parent_object_id
                                                                And Exists(Select 1 From sys.key_constraints Where object_id=a.object_id And parent_object_id=a1.object_id And unique_index_id=a1.index_id)
                                                        For Xml Path(‘‘)
                                                    ),1,1,‘‘)+
                                                ‘)‘
                    When ‘C‘ Then ‘ Check‘ +(Select definition From sys.check_constraints Where object_id=a.object_id)
                    Else ‘‘
                End As definition

            From sys.objects As a
            Where a.type In(‘PK‘,‘F‘,‘C‘,‘UQ‘)
                    And Exists(Select 1  From #Objects Where object_id=a.parent_object_id)

        --Index
        Insert Into #Columns
        Select    a.object_id ,
                a.index_id As Seq,
                3 As DefinitionType,
                ‘Create ‘+Case a.is_unique When 1 Then ‘Unique ‘ Else ‘‘ End+
                Case a.type When 1 Then ‘Clustered ‘ Else ‘Nonclustered ‘ End+
                ‘Index ‘+Quotename(a.name)+‘ On ‘+Quotename(b.name)+
                                        ‘ (‘+Stuff((Select ‘,‘+Quotename(b1.Name)+Case a1.is_descending_key When 1 Then ‘ Desc‘ Else ‘ Asc‘ End
                                                        From sys.index_columns As a1
                                                            Inner Join sys.columns As b1 On b1.object_id=a1.object_id And b1.column_id=a1.column_id
                                                        Where a1.object_id=a.object_id And a.index_id=a1.index_id And a1.is_included_column=0
                                                        For Xml Path(‘‘)
                                                    ),1,1,‘‘)+
                                        ‘)‘+
                                        Isnull(‘ Include(‘+Stuff((Select ‘,‘+Quotename(b1.Name)
                                                        From sys.index_columns As a1
                                                            Inner Join sys.columns As b1 On b1.object_id=a1.object_id And b1.column_id=a1.column_id
                                                        Where a1.object_id=a.object_id And a.index_id=a1.index_id And a1.is_included_column=1
                                                        For Xml Path(‘‘)
                                                    ),1,1,‘‘)+
                                        ‘)‘,‘‘)
                    As definition
            From sys.indexes As a
                Inner Join #Objects As b On b.object_id=a.object_id
            Where a.type>0
                    And Not Exists(Select 1 From sys.key_constraints Where parent_object_id=a.object_id And unique_index_id=a.index_id)

		--extended_properties Andy 2017-3-28 添加扩展属性
		insert into #Columns
		    select b.object_id,
					a.major_id as Seq,
					4 as DefinitionType,
					case a.minor_id
						when 0 then ‘execute sp_addextendedproperty ‘‘MS_Description‘‘,‘‘‘+convert(nvarchar(max),a.value)+‘‘‘, ‘‘user‘‘, ‘‘dbo‘‘, ‘‘table‘‘, ‘+quotename(b.name,‘‘‘‘)
						else ‘execute sp_addextendedproperty ‘‘MS_Description‘‘,‘‘‘+convert(nvarchar(max),a.value)+‘‘‘, ‘‘user‘‘, ‘‘dbo‘‘, ‘‘table‘‘, ‘+quotename(b.name,‘‘‘‘)+‘,‘‘column‘‘,‘+quotename(c.name,‘‘‘‘)
						end
				from  sys.extended_properties a
					inner join #Objects b on b.object_id=a.major_id
					inner join sys.columns c on c.object_id=b.object_id
						and c.column_id=a.minor_id
				where a.class=1

        --Print

/*
        Print ‘Use ‘+Quotename(db_name())[email protected]+‘Go‘[email protected]+‘/* 创建表结构 Andy ‘+Convert(nvarchar(10),Getdate(),120)+‘*/‘[email protected]

        Set @id=1
        While @id<[email protected]
        Begin
            Select @objectid=object_id,@ObjectName=name From #Objects Where [email protected]

            Set @[email protected]+‘--(‘+Rtrim(@id)+‘/‘+Rtrim(@Rowcount)+‘) ‘[email protected][email protected]+‘If object_id(‘‘‘+Quotename(@ObjectName)+‘‘‘) Is Null‘[email protected]+‘Begin‘[email protected][email protected]+
                    ‘Create Table ‘+Quotename(@ObjectName)[email protected][email protected]+‘(‘[email protected]
            Select @[email protected][email protected][email protected]+definition+‘,‘[email protected]
                From #Columns
                Where [email protected]
                        And DefinitionType=1
                Group By Seq,definition
                Order By Seq
            Set @sql=Substring(@sql,1,Len(@sql)-3)[email protected][email protected]+‘)‘[email protected]
            Select @[email protected][email protected][email protected]
                From #Columns
                Where [email protected]
                        And DefinitionType>1
                Group By DefinitionType,Seq,definition
                Order By Seq

            Print Substring(@sql,1,Len(@sql)-2)[email protected]+‘End‘
            Set @[email protected]+1
        End

*/
        --Modify Nr:20100510 Start
        Declare @MaxRow int

        if object_id(‘tempdb..#Print‘) Is Not Null
            Drop Table #Print

        Create Table #Print(Row int Identity(1,1) Primary Key,Sql nvarchar(4000))

        Print ‘Use ‘+Quotename(db_name())[email protected]+‘Go‘[email protected]+‘/* 创建表结构 Andy ‘+Convert(nvarchar(10),Getdate(),120)+‘*/‘[email protected]

        Set @id=1
        While @id<[email protected]
        Begin
            Select @objectid=object_id,@ObjectName=name From #Objects Where [email protected]

            Insert Into #Print(Sql)
                Select @Enter+‘--(‘+Rtrim(@id)+‘/‘+Rtrim(@Rowcount)+‘) ‘[email protected][email protected]+‘If object_id(‘‘‘+Quotename(@ObjectName)+‘‘‘) Is Null‘[email protected]+‘Begin‘[email protected][email protected]+
                    ‘Create Table ‘+Quotename(@ObjectName)[email protected][email protected]+‘(‘[email protected] 

           Insert Into #Print(Sql)
            Select @[email protected]+definition+‘,‘[email protected]
                From #Columns
                Where [email protected]
                        And DefinitionType=1
                Group By Seq,definition
                Order By Seq           

            Set @MaxRow=Scope_identity()
            Update #Print
                Set Sql=Substring(sql,1,Len(sql)-3)[email protected][email protected]+‘)‘[email protected]
                Where [email protected]

            Insert Into #Print(Sql)
            Select @[email protected]
                From #Columns
                Where [email protected]
                        And DefinitionType>1
                Group By DefinitionType,Seq,definition
                Order By Seq

            if @@ROWCOUNT >0
                Set @MaxRow=Scope_identity()

            Update #Print
                Set Sql= Substring(Sql,1,Len(Sql)-2)[email protected]+‘End‘
                Where [email protected] 

            Set @[email protected]+1
        End

        Set @id=1
        While @id>0
        Begin
            Set @sql=‘‘
            Select @sql=sql From #Print Where [email protected]

            If @sql>‘‘
            Begin
                Print @sql
                Set @[email protected]+1
            end
            Else
                Set @id=0
        End

        --Modify Nr:20100510 End

        Print ‘Go‘

    Drop Table #Columns
    Drop Table #Objects

Go
时间: 2024-10-10 22:59:17

生成建表脚本up_CreateTable的相关文章

(转)SQL SERVER 生成建表脚本

https://www.cnblogs.com/champaign/p/3492510.html /****** Object: StoredProcedure [dbo].[GET_TableScript_MSSQL] Script Date: 06/15/2012 11:59:00 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGO/*====================================================

生成建表、建用户、建表空间语句

第一种方法是使用工具,如:pl/sql developer,在[工具]--[导出用户对象]出现就可以得到建表脚本.第二种方法是,sql语句. DBMS_METADATA.GET_DDL包可以得到数据库的对象的ddl脚本.如下(SQLPLUS中执行): 1.得 到一个表的ddl语句: SET SERVEROUTPUT ON SET LINESIZE 1000 SET FEEDBACK OFF set long 999999             ------显示不完整 SET PAGESIZE

SQL_使用DBMS_METADATA.GET_DDL生成建表语句

原创作品,出自 "深蓝的blog" 博客,欢迎转载,转载时请务必注明以下出处,否则追究版权法律责任. 深蓝的blog:http://blog.csdn.net/huangyanlong/article/details/43988377 今天在群里学来一着,通过DBMS_METADATA.GET_DDL来生成建表或视图的sql语句. (1).生成创建表的sql语句 SQL> set long 20000; SQL> SELECT DBMS_METADATA.GET_DDL('

Excel生成建表角本

使用宏生成建表角本: Private Sub CreateFile() Dim Fcreate As Object '建表头 Dim FSO As Object Dim Fopen As Object '追加语句 Dim Dir As Object '建目录 Dim Fcreate_run As Object '总调角本 Set mysheet1 = Workbooks(ThisWorkbook.Name).Sheets(1) 'Sheets1 Set mysheet = Workbooks(T

Oracle建表脚本记录

--删除 drop table dianfei; --创建表 create table dianfei ( uon varchar2(10) not null, mmonth varchar2(6) not null, ddf number(6,2) not null, djftime date not null, djfzt varchar2(3) not null, dsyjf date not null ); --注释 comment on table dianfei is '电表'; c

生成建表sql的excel语句

="[" & B27 & "]" & " " & C27 & " " & IF(D27="Y","NULL","NOT NULL") & IF(E27="Y", " "&"PRIMARY KEY","") & IF(J

mysql初始化数据库建表脚本

set names utf8; set global validate_password.policy=LOW;set global validate_password.length=6;CREATE DATABASE If Not Exists ai_teaching Character Set UTF8;CREATE USER 'ai'@'localhost' IDENTIFIED BY 'shixun';GRANT all ON ai_teaching.* TO 'ai'@'localho

在线ER模型设计:可视化MySQL数据库建表及操作

概述 ER模型使用可视化了实体存储的信息,以及直观的呈现了实体与实体的关系,在我们实际的应用系统开发过程中新建ER模型可以更好的理解业务模型,为以后的开发维护工作起到归纳总结的作用. [Freedgo Desgin]()是一款轻松.快速.协作地创建各种专业图表工具.让您在线创建流程图.系统部署图.软件架构图.UML.BPMN.ER模型,DFD,组织图,软件流程图,图表.免费试用.使用Freedgo Design创建数据库ER模型目前支持MySQL及基本的SQL语句建表.后期会进行功能拓展以支持S

MySQL 建库、建用户及建表事项

1,MySQL建库语句比较简单,一句话: 1 create database tppamltest3 2,创建用户及授权: 1 insert into mysql.user(Host,User,Password,ssl_cipher,x509_issuer,x509_subject) values("localhost","用户名",password("密码"),"","",""); 2