生成SQL使用Query为现有表创build脚本
我需要能够获得SQL Server 2008中现有表的CREATE脚本 。 我假设我可以通过以某种方式查询sys.tables来做到这一点,但是这并没有将我的CREATE脚本数据返回给我。
可能这对你有帮助。 这个脚本为任何表生成索引,FK,PK和通用结构。
例如 –
DDL:
CREATE TABLE [dbo].[WorkOut]( [WorkOutID] [bigint] IDENTITY(1,1) NOT NULL, [TimeSheetDate] [datetime] NOT NULL, [DateOut] [datetime] NOT NULL, [EmployeeID] [int] NOT NULL, [IsMainWorkPlace] [bit] NOT NULL, [DepartmentUID] [uniqueidentifier] NOT NULL, [WorkPlaceUID] [uniqueidentifier] NULL, [TeamUID] [uniqueidentifier] NULL, [WorkShiftCD] [nvarchar](10) NULL, [WorkHours] [real] NULL, [AbsenceCode] [varchar](25) NULL, [PaymentType] [char](2) NULL, [CategoryID] [int] NULL, [Year] AS (datepart(year,[TimeSheetDate])), CONSTRAINT [PK_WorkOut] PRIMARY KEY CLUSTERED ( [WorkOutID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] ALTER TABLE [dbo].[WorkOut] ADD CONSTRAINT [DF__WorkOut__IsMainW__2C1E8537] DEFAULT ((1)) FOR [IsMainWorkPlace] ALTER TABLE [dbo].[WorkOut] WITH CHECK ADD CONSTRAINT [FK_WorkOut_Employee_EmployeeID] FOREIGN KEY([EmployeeID]) REFERENCES [dbo].[Employee] ([EmployeeID]) ALTER TABLE [dbo].[WorkOut] CHECK CONSTRAINT [FK_WorkOut_Employee_EmployeeID]
查询:
DECLARE @table_name SYSNAME SELECT @table_name = 'dbo.WorkOut' DECLARE @object_name SYSNAME , @object_id INT SELECT @object_name = '[' + s.name + '].[' + o.name + ']' , @object_id = o.[object_id] FROM sys.objects o WITH (NOWAIT) JOIN sys.schemas s WITH (NOWAIT) ON o.[schema_id] = s.[schema_id] WHERE s.name + '.' + o.name = @table_name AND o.[type] = 'U' AND o.is_ms_shipped = 0 DECLARE @SQL NVARCHAR(MAX) = '' ;WITH index_column AS ( SELECT ic.[object_id] , ic.index_id , ic.is_descending_key , ic.is_included_column , c.name FROM sys.index_columns ic WITH (NOWAIT) JOIN sys.columns c WITH (NOWAIT) ON ic.[object_id] = c.[object_id] AND ic.column_id = c.column_id WHERE ic.[object_id] = @object_id ), fk_columns AS ( SELECT k.constraint_object_id , cname = c.name , rcname = rc.name FROM sys.foreign_key_columns k WITH (NOWAIT) JOIN sys.columns rc WITH (NOWAIT) ON rc.[object_id] = k.referenced_object_id AND rc.column_id = k.referenced_column_id JOIN sys.columns c WITH (NOWAIT) ON c.[object_id] = k.parent_object_id AND c.column_id = k.parent_column_id WHERE k.parent_object_id = @object_id ) SELECT @SQL = 'CREATE TABLE ' + @object_name + CHAR(13) + '(' + CHAR(13) + STUFF(( SELECT CHAR(9) + ', [' + c.name + '] ' + CASE WHEN c.is_computed = 1 THEN 'AS ' + cc.[definition] ELSE UPPER(tp.name) + CASE WHEN tp.name IN ('varchar', 'char', 'varbinary', 'binary', 'text') THEN '(' + CASE WHEN c.max_length = -1 THEN 'MAX' ELSE CAST(c.max_length AS VARCHAR(5)) END + ')' WHEN tp.name IN ('nvarchar', 'nchar', 'ntext') THEN '(' + CASE WHEN c.max_length = -1 THEN 'MAX' ELSE CAST(c.max_length / 2 AS VARCHAR(5)) END + ')' WHEN tp.name IN ('datetime2', 'time2', 'datetimeoffset') THEN '(' + CAST(c.scale AS VARCHAR(5)) + ')' WHEN tp.name = 'decimal' THEN '(' + CAST(c.[precision] AS VARCHAR(5)) + ',' + CAST(c.scale AS VARCHAR(5)) + ')' ELSE '' END + CASE WHEN c.collation_name IS NOT NULL THEN ' COLLATE ' + c.collation_name ELSE '' END + CASE WHEN c.is_nullable = 1 THEN ' NULL' ELSE ' NOT NULL' END + CASE WHEN dc.[definition] IS NOT NULL THEN ' DEFAULT' + dc.[definition] ELSE '' END + CASE WHEN ic.is_identity = 1 THEN ' IDENTITY(' + CAST(ISNULL(ic.seed_value, '0') AS CHAR(1)) + ',' + CAST(ISNULL(ic.increment_value, '1') AS CHAR(1)) + ')' ELSE '' END END + CHAR(13) FROM sys.columns c WITH (NOWAIT) JOIN sys.types tp WITH (NOWAIT) ON c.user_type_id = tp.user_type_id LEFT JOIN sys.computed_columns cc WITH (NOWAIT) ON c.[object_id] = cc.[object_id] AND c.column_id = cc.column_id LEFT JOIN sys.default_constraints dc WITH (NOWAIT) ON c.default_object_id != 0 AND c.[object_id] = dc.parent_object_id AND c.column_id = dc.parent_column_id LEFT JOIN sys.identity_columns ic WITH (NOWAIT) ON c.is_identity = 1 AND c.[object_id] = ic.[object_id] AND c.column_id = ic.column_id WHERE c.[object_id] = @object_id ORDER BY c.column_id FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, CHAR(9) + ' ') + ISNULL((SELECT CHAR(9) + ', CONSTRAINT [' + k.name + '] PRIMARY KEY (' + (SELECT STUFF(( SELECT ', [' + c.name + '] ' + CASE WHEN ic.is_descending_key = 1 THEN 'DESC' ELSE 'ASC' END FROM sys.index_columns ic WITH (NOWAIT) JOIN sys.columns c WITH (NOWAIT) ON c.[object_id] = ic.[object_id] AND c.column_id = ic.column_id WHERE ic.is_included_column = 0 AND ic.[object_id] = k.parent_object_id AND ic.index_id = k.unique_index_id FOR XML PATH(N''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '')) + ')' + CHAR(13) FROM sys.key_constraints k WITH (NOWAIT) WHERE k.parent_object_id = @object_id AND k.[type] = 'PK'), '') + ')' + CHAR(13) + ISNULL((SELECT ( SELECT CHAR(13) + 'ALTER TABLE ' + @object_name + ' WITH' + CASE WHEN fk.is_not_trusted = 1 THEN ' NOCHECK' ELSE ' CHECK' END + ' ADD CONSTRAINT [' + fk.name + '] FOREIGN KEY(' + STUFF(( SELECT ', [' + k.cname + ']' FROM fk_columns k WHERE k.constraint_object_id = fk.[object_id] FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '') + ')' + ' REFERENCES [' + SCHEMA_NAME(ro.[schema_id]) + '].[' + ro.name + '] (' + STUFF(( SELECT ', [' + k.rcname + ']' FROM fk_columns k WHERE k.constraint_object_id = fk.[object_id] FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '') + ')' + CASE WHEN fk.delete_referential_action = 1 THEN ' ON DELETE CASCADE' WHEN fk.delete_referential_action = 2 THEN ' ON DELETE SET NULL' WHEN fk.delete_referential_action = 3 THEN ' ON DELETE SET DEFAULT' ELSE '' END + CASE WHEN fk.update_referential_action = 1 THEN ' ON UPDATE CASCADE' WHEN fk.update_referential_action = 2 THEN ' ON UPDATE SET NULL' WHEN fk.update_referential_action = 3 THEN ' ON UPDATE SET DEFAULT' ELSE '' END + CHAR(13) + 'ALTER TABLE ' + @object_name + ' CHECK CONSTRAINT [' + fk.name + ']' + CHAR(13) FROM sys.foreign_keys fk WITH (NOWAIT) JOIN sys.objects ro WITH (NOWAIT) ON ro.[object_id] = fk.referenced_object_id WHERE fk.parent_object_id = @object_id FOR XML PATH(N''), TYPE).value('.', 'NVARCHAR(MAX)')), '') + ISNULL(((SELECT CHAR(13) + 'CREATE' + CASE WHEN i.is_unique = 1 THEN ' UNIQUE' ELSE '' END + ' NONCLUSTERED INDEX [' + i.name + '] ON ' + @object_name + ' (' + STUFF(( SELECT ', [' + c.name + ']' + CASE WHEN c.is_descending_key = 1 THEN ' DESC' ELSE ' ASC' END FROM index_column c WHERE c.is_included_column = 0 AND c.index_id = i.index_id FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '') + ')' + ISNULL(CHAR(13) + 'INCLUDE (' + STUFF(( SELECT ', [' + c.name + ']' FROM index_column c WHERE c.is_included_column = 1 AND c.index_id = i.index_id FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '') + ')', '') + CHAR(13) FROM sys.indexes i WITH (NOWAIT) WHERE i.[object_id] = @object_id AND i.is_primary_key = 0 AND i.[type] = 2 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') ), '') PRINT @SQL --EXEC sys.sp_executesql @SQL
输出:
CREATE TABLE [dbo].[WorkOut] ( [WorkOutID] BIGINT NOT NULL IDENTITY(1,1) , [TimeSheetDate] DATETIME NOT NULL , [DateOut] DATETIME NOT NULL , [EmployeeID] INT NOT NULL , [IsMainWorkPlace] BIT NOT NULL DEFAULT((1)) , [DepartmentUID] UNIQUEIDENTIFIER NOT NULL , [WorkPlaceUID] UNIQUEIDENTIFIER NULL , [TeamUID] UNIQUEIDENTIFIER NULL , [WorkShiftCD] NVARCHAR(10) COLLATE Cyrillic_General_CI_AS NULL , [WorkHours] REAL NULL , [AbsenceCode] VARCHAR(25) COLLATE Cyrillic_General_CI_AS NULL , [PaymentType] CHAR(2) COLLATE Cyrillic_General_CI_AS NULL , [CategoryID] INT NULL , [Year] AS (datepart(year,[TimeSheetDate])) , CONSTRAINT [PK_WorkOut] PRIMARY KEY ([WorkOutID] ASC) ) ALTER TABLE [dbo].[WorkOut] WITH CHECK ADD CONSTRAINT [FK_WorkOut_Employee_EmployeeID] FOREIGN KEY([EmployeeID]) REFERENCES [dbo].[Employee] ([EmployeeID]) ALTER TABLE [dbo].[WorkOut] CHECK CONSTRAINT [FK_WorkOut_Employee_EmployeeID] CREATE NONCLUSTERED INDEX [IX_WorkOut_WorkShiftCD_AbsenceCode] ON [dbo].[WorkOut] ([WorkShiftCD] ASC, [AbsenceCode] ASC) INCLUDE ([WorkOutID], [WorkHours])
也检查这篇文章 –
如何为现有表生成CREATE TABLE脚本:第1部分
你的意思是你想创build一个TSQL脚本来生成一个CREATE脚本,或者使用SQL SERVER Management Studio中的pipe理工具来生成一个Create脚本?
如果是后者,只需右键单击一个表,然后select脚本表另存为 – >创build到 – >新查询窗口。
如果你想整个数据库脚本,然后右键单击数据库,然后select任务 – >生成脚本…然后按照向导
否则就是从各种系统表中select各种有趣的事情。
我意识到这个问题是旧的,但最近刚刚出现在我刚刚跑过的search中,所以我想我会提供一个替代上述答案。
如果您正在寻找在.Net中以编程方式生成create
脚本,我强烈build议查看服务器pipe理对象 (SMO)或分布式pipe理对象 (DMO) – 取决于您使用的是哪个版本的SQL Server(前者是2005+ ,后者2000年)。 使用这些库,脚本表的操作非常简单:
Server server = new Server("."); Database northwind = server.Databases["Northwind"]; Table categories = northwind.Tables["Categories"]; StringCollection script = categories.Script(); string[] scriptArray = new string[script.Count]; script.CopyTo(scriptArray, 0);
这里是一个博客文章,更多的信息。
试试sp_helptext等价于表?
“最简单的方法是使用SQLpipe理工作室的内置function”,但是…我用一个函数和几个过程来解决它。 例如,要获取名为“table_name”的表的创build表,您必须执行名为sp_ppinScriptTabla的过程:
Exec sp_ppinScriptTabla 'table_name'
这里是tsql脚本代码:
Use Master GO Create Function sp_ppinTipoLongitud ( @xtype int, @length int, @isnullable int ) Returns Varchar(512) As Begin -- Función que a partir de un tipo de datos y una logitud, devuelve el texto del tipo. -- Por ejemplo: para xtype=varchar y length=10 devolverá "varchar(10)" Declare @ret varchar(512) Set @ret = '' Select @ret = t.name + Case When name in ('varchar', 'nvarchar', 'char', 'nchar') Then '(' + Convert(varchar, @length) + ')' Else '' End + ' ' + Case @isnullable When 1 Then 'NULL' Else 'NOT NULL' End From systypes t Where t.xtype = @xtype Return @ret End GO Create Procedure sp_ppinScriptLlavesForaneas ( @vchTabla sysname, @vchResultado varchar(8000) output ) AS Begin DECLARE @tmpFK table( TablaF sysname, TablaR sysname, ColF sysname, ColR sysname, FKName sysname) -- obtengo las llaves foraneas en @vchForeign Declare @vchForeign varchar(8000), @FKName sysname, @vchColumnasF varchar(4000), @vchColumnasR varchar(4000), @ColF sysname, @ColR sysname Declare @vchTemp varchar(1000), @TablaR sysname Insert into @tmpFK Select TablaF.name AS TablaF, TablaR.name AS TablaR, ColF.name AS ColF, ColR.name AS ColR, ofk.name AS FKName From sysforeignkeys fk, sysobjects ofk, sysobjects TablaF, sysobjects TablaR, syscolumns ColF, syscolumns ColR Where TablaF.name = @vchTabla And ofk.id = fk.constid And TablaF.id = fk.fkeyid And TablaR.id = fk.rkeyid And ColF.id = TablaF.id And ColF.colid = fk.fkey And ColR.id = TablaR.id And ColR.colid = fk.rkey order by FKName Set @vchForeign = '' While Exists ( Select * From @tmpFK ) Begin Select Top 1 @FKName = FKName From @tmpFK Set @vchColumnasF = '' Set @vchColumnasR = '' While Exists ( Select * From @tmpFK Where FKName = @FKName ) Begin Select Top 1 @ColF = ColF, @ColR = ColR, @TablaR = TablaR From @tmpFK Where FKName = @FKName Delete From @tmpFK Where ColF = @ColF And ColR = @ColR And TablaR = @TablaR And FKName = @FKName Set @vchColumnasF = @vchColumnasF + @ColF + ', ' Set @vchColumnasR = @vchColumnasR + @ColR + ', ' End Set @vchColumnasF = LEFT(@vchColumnasF, LEN(@vchColumnasF) - 1) Set @vchColumnasR = LEFT(@vchColumnasR, LEN(@vchColumnasR) - 1) Set @vchTemp = 'Constraint ' + @FKName + ' Foreign Key (' + @vchColumnasF + ') ' Set @vchTemp = @vchTemp + 'References ' + @TablaR + ' (' + @vchColumnasR + ')' Set @vchForeign = @vchForeign + char(9) + @vchTemp + ',' + char(13) End Select @vchResultado = Case When Len(@vchForeign) >=2 Then Left(@vchForeign, Len(@vchForeign) - 2) Else @vchForeign End End GO Create Procedure sp_ppinScriptTabla ( @vchTabla sysname ) AS Set nocount on -- Obtengo las foreign keys Declare @foreign varchar(8000) Exec sp_ppinScriptLlavesForaneas @vchTabla, @foreign output -- SELECT que devuelve el script de Create Table de la tabla Select 'Create ' + Case o.xtype When 'U' Then 'Table' When 'P' Then 'Procedure' Else '??' End + ' ' + @vchTabla + char(13) + '(' From sysobjects o Where o.name = @vchTabla Union all -- Campos + identitys + DEFAULTS select char(9) + c.name + ' ' + -- Nombre dbo.sp_ppinTipoLongitud(t.xtype, c.length, c.isnullable) + -- Tipo(longitud) Case When c.colstat & 1 = 1 -- Identity (si aplica) Then ' Identity(' + convert(varchar, ident_seed(@vchTabla)) + ',' + Convert(varchar, ident_incr(@vchTabla)) + ')' Else '' End + Case When not od.name is null -- Defaults (si aplica) Then ' Constraint ' + od.name + ' Default ' + replace(replace(cd.text, '((', '('), '))', ')') Else '' End + ', ' from sysobjects o, syscolumns c LEFT OUTER JOIN sysobjects od On od.id = c.cdefault LEFT OUTER join syscomments cd On cd.id = od.id, systypes t where o.id = object_id(@vchTabla) and o.id = c.id and c.xtype = t.xtype Union all -- Primary Keys y Unique keys select char(9) + 'Constraint ' + o.name + ' ' + Case o.xtype When 'PK' Then 'Primary Key' Else 'Unique' End + ' ' + dbo.sp_ppinCamposIndice (db_name(), @vchTabla, i.indid) + ', ' from sysobjects o, sysindexes i where o.parent_obj = object_id(@vchTabla) and o.xtype in ('PK','UQ') and i.id = o.parent_obj and o.name = i.name Union all -- Check constraints select char(9) + 'Constraint ' + o.name + ' Check ' + c.text + ', ' from sysobjects o, syscomments c where o.parent_obj = object_id(@vchTabla) and o.xtype in ('C') and o.id = c.id Union all -- Foreign keys Select @foreign Union all Select ')' Set nocount off GO
您忘记了包含sp_ppinCamposIndice
的存储过程或函数脚本
试试这个(使用“结果到文本”):
SELECT ISNULL(smsp.definition, ssmsp.definition) AS [Definition] FROM sys.all_objects AS sp LEFT OUTER JOIN sys.sql_modules AS smsp ON smsp.object_id = sp.object_id LEFT OUTER JOIN sys.system_sql_modules AS ssmsp ON ssmsp.object_id = sp.object_id WHERE (sp.type = N'V' OR sp.type = N'P' OR sp.type = N'RF' OR sp.type=N'PC')and(sp.name=N'YourObjectName' and SCHEMA_NAME(sp.schema_id)=N'dbo')
- C:检查约束
- D:默认约束
- F:外键约束
- L:日志
- P:存储过程
- PK:主键约束
- RF:复制filter存储过程
- S:系统表
- TR:触发器
- U:用户表
- UQ:唯一约束
- V:查看
- X:扩展存储过程
干杯,
最简单的方法是使用SQL Management Studio的内置function。
右键单击数据库,转到任务,生成脚本,然后遍历向导。 你可以select脚本的对象,它会为你一切。
现在,如果你想让自己的脚本做同样的事情,你可能需要做很多工作。
因为我们提供的是你所问的
如果您在.Net中,则应该查看Visual Studio中的“数据库发布向导”。 简单的方法来将您的表/数据脚本编写为文本文件。
http://www.codeplex.com/sqlhost/Wiki/View.aspx?title=Database%20Publishing%20Wizard
使用SSMS,最简单的方法你也可以configuration它的选项(例如,sorting,语法,下降…创build)
否则,CodePlex上的SSMS Tools Pack或DbFriend可以帮助您生成脚本
在这个问题中查看我的答案: 如何在SQL Server中使用SQL查询生成表的创build脚本
使用这个查询:
DROP FUNCTION [dbo].[Get_Table_Script] Go Create Function Get_Table_Script ( @vsTableName varchar(50) ) Returns VarChar(Max) With ENCRYPTION Begin Declare @ScriptCommand varchar(Max) Select @ScriptCommand = ' Create Table [' + SO.name + '] (' + o.list + ')' + ( Case When TC.Constraint_Name IS NULL Then '' Else 'ALTER TABLE ' + SO.Name + ' ADD CONSTRAINT ' + TC.Constraint_Name + ' PRIMARY KEY ' + ' (' + LEFT(j.List, Len(j.List)-1) + ')' End ) From sysobjects As SO Cross Apply ( Select ' [' + column_name + '] ' + data_type + ( Case data_type When 'sql_variant' Then '' When 'text' Then '' When 'decimal' Then '(' + Cast( numeric_precision_radix As varchar ) + ', ' + Cast( numeric_scale As varchar ) + ') ' Else Coalesce( '(' + Case When character_maximum_length = -1 Then 'MAX' Else Cast( character_maximum_length As VarChar ) End + ')' , '' ) End ) + ' ' + ( Case When Exists ( Select id From syscolumns Where ( object_name(id) = SO.name ) And ( name = column_name ) And ( columnproperty(id,name,'IsIdentity') = 1 ) ) Then 'IDENTITY(' + Cast( ident_seed(SO.name) As varchar ) + ',' + Cast( ident_incr(SO.name) As varchar ) + ')' Else '' End ) + ' ' + ( Case When IS_NULLABLE = 'No' Then 'NOT ' Else '' End ) + 'NULL ' + ( Case When information_schema.columns.COLUMN_DEFAULT IS NOT NULL Then 'DEFAULT ' + information_schema.columns.COLUMN_DEFAULT ELse '' End ) + ', ' From information_schema.columns Where ( table_name = SO.name ) Order by ordinal_position FOR XML PATH('')) o (list) Inner Join information_schema.table_constraints As TC On ( ( TC.Table_name = SO.Name ) AND ( TC.Constraint_Type = 'PRIMARY KEY' ) And ( TC.TABLE_NAME = @vsTableName ) ) Cross Apply ( Select '[' + Column_Name + '], ' From information_schema.key_column_usage As kcu Where ( kcu.Constraint_Name = TC.Constraint_Name ) Order By ORDINAL_POSITION FOR XML PATH('') ) As j (list) Where ( xtype = 'U' ) AND ( Name NOT IN ('dtproperties') ) Return @ScriptCommand End
你可以像这样开启这个Function
:
Select [dbo].Get_Table_Script '<Your_Table_Name>'
这里是@Devart的答案的一个小的变化,所以你可以得到临时表的CREATE脚本。
请注意,由于@SQLvariables是NVARCHAR(MAX)
数据types,因此您可能无法仅使用SSMS将结果复制到结果中。 请看这个问题 ,看看如何获得MAX字段的完整值。
DECLARE @temptable_objectid INT = OBJECT_ID('tempdb.db.#Temp'); DECLARE @object_name SYSNAME , @object_id INT SELECT @object_name = '[' + s.name + '].[' + o.name + ']' , @object_id = o.[object_id] FROM tempdb.sys.objects o WITH (NOWAIT) JOIN tempdb.sys.schemas s WITH (NOWAIT) ON o.[schema_id] = s.[schema_id] WHERE object_id = @temptable_objectid DECLARE @SQL NVARCHAR(MAX) = '' ;WITH index_column AS ( SELECT ic.[object_id] , ic.index_id , ic.is_descending_key , ic.is_included_column , c.name FROM tempdb.sys.index_columns ic WITH (NOWAIT) JOIN tempdb.sys.columns c WITH (NOWAIT) ON ic.[object_id] = c.[object_id] AND ic.column_id = c.column_id WHERE ic.[object_id] = @object_id ), fk_columns AS ( SELECT k.constraint_object_id , cname = c.name , rcname = rc.name FROM tempdb.sys.foreign_key_columns k WITH (NOWAIT) JOIN tempdb.sys.columns rc WITH (NOWAIT) ON rc.[object_id] = k.referenced_object_id AND rc.column_id = k.referenced_column_id JOIN tempdb.sys.columns c WITH (NOWAIT) ON c.[object_id] = k.parent_object_id AND c.column_id = k.parent_column_id WHERE k.parent_object_id = @object_id ) SELECT @SQL = 'CREATE TABLE ' + @object_name + CHAR(13) + '(' + CHAR(13) + STUFF(( SELECT CHAR(9) + ', [' + c.name + '] ' + CASE WHEN c.is_computed = 1 THEN 'AS ' + cc.[definition] ELSE UPPER(tp.name) + CASE WHEN tp.name IN ('varchar', 'char', 'varbinary', 'binary', 'text') THEN '(' + CASE WHEN c.max_length = -1 THEN 'MAX' ELSE CAST(c.max_length AS VARCHAR(5)) END + ')' WHEN tp.name IN ('nvarchar', 'nchar', 'ntext') THEN '(' + CASE WHEN c.max_length = -1 THEN 'MAX' ELSE CAST(c.max_length / 2 AS VARCHAR(5)) END + ')' WHEN tp.name IN ('datetime2', 'time2', 'datetimeoffset') THEN '(' + CAST(c.scale AS VARCHAR(5)) + ')' WHEN tp.name = 'decimal' THEN '(' + CAST(c.[precision] AS VARCHAR(5)) + ',' + CAST(c.scale AS VARCHAR(5)) + ')' ELSE '' END + CASE WHEN c.collation_name IS NOT NULL THEN ' COLLATE ' + c.collation_name ELSE '' END + CASE WHEN c.is_nullable = 1 THEN ' NULL' ELSE ' NOT NULL' END + CASE WHEN dc.[definition] IS NOT NULL THEN ' DEFAULT' + dc.[definition] ELSE '' END + CASE WHEN ic.is_identity = 1 THEN ' IDENTITY(' + CAST(ISNULL(ic.seed_value, '0') AS CHAR(1)) + ',' + CAST(ISNULL(ic.increment_value, '1') AS CHAR(1)) + ')' ELSE '' END END + CHAR(13) FROM tempdb.sys.columns c WITH (NOWAIT) JOIN tempdb.sys.types tp WITH (NOWAIT) ON c.user_type_id = tp.user_type_id LEFT JOIN tempdb.sys.computed_columns cc WITH (NOWAIT) ON c.[object_id] = cc.[object_id] AND c.column_id = cc.column_id LEFT JOIN tempdb.sys.default_constraints dc WITH (NOWAIT) ON c.default_object_id != 0 AND c.[object_id] = dc.parent_object_id AND c.column_id = dc.parent_column_id LEFT JOIN tempdb.sys.identity_columns ic WITH (NOWAIT) ON c.is_identity = 1 AND c.[object_id] = ic.[object_id] AND c.column_id = ic.column_id WHERE c.[object_id] = @object_id ORDER BY c.column_id FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, CHAR(9) + ' ') + ISNULL((SELECT CHAR(9) + ', CONSTRAINT [' + k.name + '] PRIMARY KEY (' + (SELECT STUFF(( SELECT ', [' + c.name + '] ' + CASE WHEN ic.is_descending_key = 1 THEN 'DESC' ELSE 'ASC' END FROM tempdb.sys.index_columns ic WITH (NOWAIT) JOIN tempdb.sys.columns c WITH (NOWAIT) ON c.[object_id] = ic.[object_id] AND c.column_id = ic.column_id WHERE ic.is_included_column = 0 AND ic.[object_id] = k.parent_object_id AND ic.index_id = k.unique_index_id FOR XML PATH(N''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '')) + ')' + CHAR(13) FROM tempdb.sys.key_constraints k WITH (NOWAIT) WHERE k.parent_object_id = @object_id AND k.[type] = 'PK'), '') + ')' + CHAR(13) + ISNULL((SELECT ( SELECT CHAR(13) + 'ALTER TABLE ' + @object_name + ' WITH' + CASE WHEN fk.is_not_trusted = 1 THEN ' NOCHECK' ELSE ' CHECK' END + ' ADD CONSTRAINT [' + fk.name + '] FOREIGN KEY(' + STUFF(( SELECT ', [' + k.cname + ']' FROM fk_columns k WHERE k.constraint_object_id = fk.[object_id] FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '') + ')' + ' REFERENCES [' + SCHEMA_NAME(ro.[schema_id]) + '].[' + ro.name + '] (' + STUFF(( SELECT ', [' + k.rcname + ']' FROM fk_columns k WHERE k.constraint_object_id = fk.[object_id] FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '') + ')' + CASE WHEN fk.delete_referential_action = 1 THEN ' ON DELETE CASCADE' WHEN fk.delete_referential_action = 2 THEN ' ON DELETE SET NULL' WHEN fk.delete_referential_action = 3 THEN ' ON DELETE SET DEFAULT' ELSE '' END + CASE WHEN fk.update_referential_action = 1 THEN ' ON UPDATE CASCADE' WHEN fk.update_referential_action = 2 THEN ' ON UPDATE SET NULL' WHEN fk.update_referential_action = 3 THEN ' ON UPDATE SET DEFAULT' ELSE '' END + CHAR(13) + 'ALTER TABLE ' + @object_name + ' CHECK CONSTRAINT [' + fk.name + ']' + CHAR(13) FROM tempdb.sys.foreign_keys fk WITH (NOWAIT) JOIN tempdb.sys.objects ro WITH (NOWAIT) ON ro.[object_id] = fk.referenced_object_id WHERE fk.parent_object_id = @object_id FOR XML PATH(N''), TYPE).value('.', 'NVARCHAR(MAX)')), '') + ISNULL(((SELECT CHAR(13) + 'CREATE' + CASE WHEN i.is_unique = 1 THEN ' UNIQUE' ELSE '' END + ' NONCLUSTERED INDEX [' + i.name + '] ON ' + @object_name + ' (' + STUFF(( SELECT ', [' + c.name + ']' + CASE WHEN c.is_descending_key = 1 THEN ' DESC' ELSE ' ASC' END FROM index_column c WHERE c.is_included_column = 0 AND c.index_id = i.index_id FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '') + ')' + ISNULL(CHAR(13) + 'INCLUDE (' + STUFF(( SELECT ', [' + c.name + ']' FROM index_column c WHERE c.is_included_column = 1 AND c.index_id = i.index_id FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '') + ')', '') + CHAR(13) FROM tempdb.sys.indexes i WITH (NOWAIT) WHERE i.[object_id] = @object_id AND i.is_primary_key = 0 AND i.[type] = 2 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') ), '') SELECT @SQL