Export database schema into SQL file - sql

Is it possible in MS SQL Server 2008 to export database structure into a T-SQL file?
I want to export not only tables schema but also primary keys, foreign keys, constraints, indexes, stored procedures, user defined types/functions.
Also I don't want the data to be present in this T-SQL file.
Is there any way to achieve that?

You can generate scripts to a file via SQL Server Management Studio, here are the steps:
Right click the database you want to generate scripts for (not the table) and select tasks - generate scripts
Next, select the requested table/tables, views, stored procedures, etc (from select specific database objects)
Click advanced - select the types of data to script
Click Next and finish
MSDN Generate Scripts
When generating the scripts, there is an area that will allow you to script, constraints, keys, etc. From SQL Server 2008 R2 there is an Advanced Option under scripting:

In the picture you can see. In the set script options, choose the last option: Types of data to script you click at the right side and you choose what you want.
This is the option you should choose to export a schema and data

Have you tried the Generate Scripts (Right click, tasks, generate scripts) option in SQL Management Studio? Does that produce what you mean by a "SQL File"?

i wrote this sp to create automatically the schema with all things, pk, fk, partitions, constraints...
I wrote it to run in same sp.
IMPORTANT!!
before exec
create type TableType as table (ObjectID int)
here the SP:
create PROCEDURE [dbo].[util_ScriptTable]
#DBName SYSNAME
,#schema sysname
,#TableName SYSNAME
,#IncludeConstraints BIT = 1
,#IncludeIndexes BIT = 1
,#NewTableSchema sysname
,#NewTableName SYSNAME = NULL
,#UseSystemDataTypes BIT = 0
,#script varchar(max) output
AS
BEGIN try
if not exists (select * from sys.types where name = 'TableType')
create type TableType as table (ObjectID int)--drop type TableType
declare #sql nvarchar(max)
DECLARE #MainDefinition TABLE (FieldValue VARCHAR(200))
--DECLARE #DBName SYSNAME
DECLARE #ClusteredPK BIT
DECLARE #TableSchema NVARCHAR(255)
--SET #DBName = DB_NAME(DB_ID())
SELECT #TableName = name FROM sysobjects WHERE id = OBJECT_ID(#TableName)
DECLARE #ShowFields TABLE (FieldID INT IDENTITY(1,1)
,DatabaseName VARCHAR(100)
,TableOwner VARCHAR(100)
,TableName VARCHAR(100)
,FieldName VARCHAR(100)
,ColumnPosition INT
,ColumnDefaultValue VARCHAR(100)
,ColumnDefaultName VARCHAR(100)
,IsNullable BIT
,DataType VARCHAR(100)
,MaxLength varchar(10)
,NumericPrecision INT
,NumericScale INT
,DomainName VARCHAR(100)
,FieldListingName VARCHAR(110)
,FieldDefinition CHAR(1)
,IdentityColumn BIT
,IdentitySeed INT
,IdentityIncrement INT
,IsCharColumn BIT
,IsComputed varchar(255))
DECLARE #HoldingArea TABLE(FldID SMALLINT IDENTITY(1,1)
,Flds VARCHAR(4000)
,FldValue CHAR(1) DEFAULT(0))
DECLARE #PKObjectID TABLE(ObjectID INT)
DECLARE #Uniques TABLE(ObjectID INT)
DECLARE #HoldingAreaValues TABLE(FldID SMALLINT IDENTITY(1,1)
,Flds VARCHAR(4000)
,FldValue CHAR(1) DEFAULT(0))
DECLARE #Definition TABLE(DefinitionID SMALLINT IDENTITY(1,1)
,FieldValue VARCHAR(200))
set #sql=
'
use '+#DBName+'
SELECT distinct DB_NAME()
,inf.TABLE_SCHEMA
,inf.TABLE_NAME
,''[''+inf.COLUMN_NAME+'']'' as COLUMN_NAME
,CAST(inf.ORDINAL_POSITION AS INT)
,inf.COLUMN_DEFAULT
,dobj.name AS ColumnDefaultName
,CASE WHEN inf.IS_NULLABLE = ''YES'' THEN 1 ELSE 0 END
,inf.DATA_TYPE
,case inf.CHARACTER_MAXIMUM_LENGTH when -1 then ''max'' else CAST(inf.CHARACTER_MAXIMUM_LENGTH AS varchar) end--CAST(CHARACTER_MAXIMUM_LENGTH AS INT)
,CAST(inf.NUMERIC_PRECISION AS INT)
,CAST(inf.NUMERIC_SCALE AS INT)
,inf.DOMAIN_NAME
,inf.COLUMN_NAME + '',''
,'''' AS FieldDefinition
--caso di viste, dà come campo identity ma nn dà i valori, quindi lo ignoro
,CASE WHEN ic.object_id IS not NULL and ic.seed_value is not null THEN 1 ELSE 0 END AS IdentityColumn--CASE WHEN ic.object_id IS NULL THEN 0 ELSE 1 END AS IdentityColumn
,CAST(ISNULL(ic.seed_value,0) AS INT) AS IdentitySeed
,CAST(ISNULL(ic.increment_value,0) AS INT) AS IdentityIncrement
,CASE WHEN c.collation_name IS NOT NULL THEN 1 ELSE 0 END AS IsCharColumn
,cc.definition
from (select schema_id,object_id,name from sys.views union all select schema_id,object_id,name from sys.tables)t
--sys.tables t
join sys.schemas s on t.schema_id=s.schema_id
JOIN sys.columns c ON t.object_id=c.object_id --AND s.schema_id=c.schema_id
LEFT JOIN sys.identity_columns ic ON t.object_id=ic.object_id AND c.column_id=ic.column_id
left JOIN sys.types st ON st.system_type_id=c.system_type_id and st.principal_id=t.object_id--COALESCE(c.DOMAIN_NAME,c.DATA_TYPE) = st.name
LEFT OUTER JOIN sys.objects dobj ON dobj.object_id = c.default_object_id AND dobj.type = ''D''
left join sys.computed_columns cc on t.object_id=cc.object_id and c.column_id=cc.column_id
join INFORMATION_SCHEMA.COLUMNS inf on t.name=inf.TABLE_NAME
and s.name=inf.TABLE_SCHEMA
and c.name=inf.COLUMN_NAME
WHERE inf.TABLE_NAME = #TableName and inf.TABLE_SCHEMA=#schema
ORDER BY inf.ORDINAL_POSITION
'
print #sql
INSERT INTO #ShowFields( DatabaseName
,TableOwner
,TableName
,FieldName
,ColumnPosition
,ColumnDefaultValue
,ColumnDefaultName
,IsNullable
,DataType
,MaxLength
,NumericPrecision
,NumericScale
,DomainName
,FieldListingName
,FieldDefinition
,IdentityColumn
,IdentitySeed
,IdentityIncrement
,IsCharColumn
,IsComputed)
exec sp_executesql #sql,
N'#TableName varchar(50),#schema varchar(50)',
#TableName=#TableName,#schema=#schema
/*
SELECT #DBName--DB_NAME()
,TABLE_SCHEMA
,TABLE_NAME
,COLUMN_NAME
,CAST(ORDINAL_POSITION AS INT)
,COLUMN_DEFAULT
,dobj.name AS ColumnDefaultName
,CASE WHEN c.IS_NULLABLE = 'YES' THEN 1 ELSE 0 END
,DATA_TYPE
,CAST(CHARACTER_MAXIMUM_LENGTH AS INT)
,CAST(NUMERIC_PRECISION AS INT)
,CAST(NUMERIC_SCALE AS INT)
,DOMAIN_NAME
,COLUMN_NAME + ','
,'' AS FieldDefinition
,CASE WHEN ic.object_id IS NULL THEN 0 ELSE 1 END AS IdentityColumn
,CAST(ISNULL(ic.seed_value,0) AS INT) AS IdentitySeed
,CAST(ISNULL(ic.increment_value,0) AS INT) AS IdentityIncrement
,CASE WHEN st.collation_name IS NOT NULL THEN 1 ELSE 0 END AS IsCharColumn
FROM INFORMATION_SCHEMA.COLUMNS c
JOIN sys.columns sc ON c.TABLE_NAME = OBJECT_NAME(sc.object_id) AND c.COLUMN_NAME = sc.Name
LEFT JOIN sys.identity_columns ic ON c.TABLE_NAME = OBJECT_NAME(ic.object_id) AND c.COLUMN_NAME = ic.Name
JOIN sys.types st ON COALESCE(c.DOMAIN_NAME,c.DATA_TYPE) = st.name
LEFT OUTER JOIN sys.objects dobj ON dobj.object_id = sc.default_object_id AND dobj.type = 'D'
WHERE c.TABLE_NAME = #TableName
ORDER BY c.TABLE_NAME, c.ORDINAL_POSITION
*/
SELECT TOP 1 #TableSchema = TableOwner FROM #ShowFields
INSERT INTO #HoldingArea (Flds) VALUES('(')
INSERT INTO #Definition(FieldValue)VALUES('CREATE TABLE ' + CASE WHEN #NewTableName IS NOT NULL THEN #DBName + '.' + #NewTableSchema + '.' + #NewTableName ELSE #DBName + '.' + #TableSchema + '.' + #TableName END)
INSERT INTO #Definition(FieldValue)VALUES('(')
INSERT INTO #Definition(FieldValue)
SELECT CHAR(10) + FieldName + ' ' +
--CASE WHEN DomainName IS NOT NULL AND #UseSystemDataTypes = 0 THEN DomainName + CASE WHEN IsNullable = 1 THEN ' NULL ' ELSE ' NOT NULL ' END ELSE UPPER(DataType) +CASE WHEN IsCharColumn = 1 THEN '(' + CAST(MaxLength AS VARCHAR(10)) + ')' ELSE '' END +CASE WHEN IdentityColumn = 1 THEN ' IDENTITY(' + CAST(IdentitySeed AS VARCHAR(5))+ ',' + CAST(IdentityIncrement AS VARCHAR(5)) + ')' ELSE '' END +CASE WHEN IsNullable = 1 THEN ' NULL ' ELSE ' NOT NULL ' END +CASE WHEN ColumnDefaultName IS NOT NULL AND #IncludeConstraints = 1 THEN 'CONSTRAINT [' + ColumnDefaultName + '] DEFAULT' + UPPER(ColumnDefaultValue) ELSE '' END END + CASE WHEN FieldID = (SELECT MAX(FieldID) FROM #ShowFields) THEN '' ELSE ',' END
CASE WHEN DomainName IS NOT NULL AND #UseSystemDataTypes = 0 THEN DomainName +
CASe WHEN IsNullable = 1 THEN ' NULL '
ELSE ' NOT NULL '
END
ELSE
case when IsComputed is null then
UPPER(DataType) +
CASE WHEN IsCharColumn = 1 THEN '(' + CAST(MaxLength AS VARCHAR(10)) + ')'
ELSE
CASE WHEN DataType = 'numeric' THEN '(' + CAST(NumericPrecision AS VARCHAR(10))+','+ CAST(NumericScale AS VARCHAR(10)) + ')'
ELSE
CASE WHEN DataType = 'decimal' THEN '(' + CAST(NumericPrecision AS VARCHAR(10))+','+ CAST(NumericScale AS VARCHAR(10)) + ')'
ELSE ''
end
end
END +
CASE WHEN IdentityColumn = 1 THEN ' IDENTITY(' + CAST(IdentitySeed AS VARCHAR(5))+ ',' + CAST(IdentityIncrement AS VARCHAR(5)) + ')'
ELSE ''
END +
CASE WHEN IsNullable = 1 THEN ' NULL '
ELSE ' NOT NULL '
END +
CASE WHEN ColumnDefaultName IS NOT NULL AND #IncludeConstraints = 1 THEN 'CONSTRAINT [' + replace(ColumnDefaultName,#TableName,#NewTableName) + '] DEFAULT' + UPPER(ColumnDefaultValue)
ELSE ''
END
else
' as '+IsComputed+' '
end
END +
CASE WHEN FieldID = (SELECT MAX(FieldID) FROM #ShowFields) THEN ''
ELSE ','
END
FROM #ShowFields
IF #IncludeConstraints = 1
BEGIN
set #sql=
'
use '+#DBName+'
SELECT distinct '',CONSTRAINT ['' + #NewTableName+''_''+replace(name,#TableName,'''') + ''] FOREIGN KEY ('' + ParentColumns + '') REFERENCES ['' + ReferencedObject + '']('' + ReferencedColumns + '')''
FROM ( SELECT ReferencedObject = OBJECT_NAME(fk.referenced_object_id), ParentObject = OBJECT_NAME(parent_object_id),fk.name
, REVERSE(SUBSTRING(REVERSE(( SELECT cp.name + '',''
FROM sys.foreign_key_columns fkc
JOIN sys.columns cp ON fkc.parent_object_id = cp.object_id AND fkc.parent_column_id = cp.column_id
WHERE fkc.constraint_object_id = fk.object_id FOR XML PATH('''') )), 2, 8000)) ParentColumns,
REVERSE(SUBSTRING(REVERSE(( SELECT cr.name + '',''
FROM sys.foreign_key_columns fkc
JOIN sys.columns cr ON fkc.referenced_object_id = cr.object_id AND fkc.referenced_column_id = cr.column_id
WHERE fkc.constraint_object_id = fk.object_id FOR XML PATH('''') )), 2, 8000)) ReferencedColumns
FROM sys.foreign_keys fk
inner join sys.schemas s on fk.schema_id=s.schema_id and s.name=#schema) a
WHERE ParentObject = #TableName
'
print #sql
INSERT INTO #Definition(FieldValue)
exec sp_executesql #sql,
N'#TableName varchar(50),#NewTableName varchar(50),#schema varchar(50)',
#TableName=#TableName,#NewTableName=#NewTableName,#schema=#schema
/*
SELECT ',CONSTRAINT [' + name + '] FOREIGN KEY (' + ParentColumns + ') REFERENCES [' + ReferencedObject + '](' + ReferencedColumns + ')'
FROM ( SELECT ReferencedObject = OBJECT_NAME(fk.referenced_object_id), ParentObject = OBJECT_NAME(parent_object_id),fk.name
, REVERSE(SUBSTRING(REVERSE(( SELECT cp.name + ','
FROM sys.foreign_key_columns fkc
JOIN sys.columns cp ON fkc.parent_object_id = cp.object_id AND fkc.parent_column_id = cp.column_id
WHERE fkc.constraint_object_id = fk.object_id FOR XML PATH('') )), 2, 8000)) ParentColumns,
REVERSE(SUBSTRING(REVERSE(( SELECT cr.name + ','
FROM sys.foreign_key_columns fkc
JOIN sys.columns cr ON fkc.referenced_object_id = cr.object_id AND fkc.referenced_column_id = cr.column_id
WHERE fkc.constraint_object_id = fk.object_id FOR XML PATH('') )), 2, 8000)) ReferencedColumns
FROM sys.foreign_keys fk ) a
WHERE ParentObject = #TableName
*/
set #sql=
'
use '+#DBName+'
SELECT distinct '',CONSTRAINT ['' + #NewTableName+''_''+replace(c.name,#TableName,'''') + ''] CHECK '' + definition
FROM sys.check_constraints c join sys.schemas s on c.schema_id=s.schema_id and s.name=#schema
WHERE OBJECT_NAME(parent_object_id) = #TableName
'
print #sql
INSERT INTO #Definition(FieldValue)
exec sp_executesql #sql,
N'#TableName varchar(50),#NewTableName varchar(50),#schema varchar(50)',
#TableName=#TableName,#NewTableName=#NewTableName,#schema=#schema
/*
SELECT ',CONSTRAINT [' + name + '] CHECK ' + definition FROM sys.check_constraints
WHERE OBJECT_NAME(parent_object_id) = #TableName
*/
set #sql=
'
use '+#DBName+'
SELECT DISTINCT PKObject = cco.object_id
FROM sys.key_constraints cco
JOIN sys.index_columns cc ON cco.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id
JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
join sys.schemas s on cco.schema_id=s.schema_id and s.name=#schema
WHERE OBJECT_NAME(parent_object_id) = #TableName AND i.type = 1 AND is_primary_key = 1
'
print #sql
INSERT INTO #PKObjectID(ObjectID)
exec sp_executesql #sql,
N'#TableName varchar(50),#schema varchar(50)',
#TableName=#TableName,#schema=#schema
/*
SELECT DISTINCT PKObject = cco.object_id
FROM sys.key_constraints cco
JOIN sys.index_columns cc ON cco.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id
JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
WHERE OBJECT_NAME(parent_object_id) = #TableName AND i.type = 1 AND is_primary_key = 1
*/
set #sql=
'
use '+#DBName+'
SELECT DISTINCT PKObject = cco.object_id
FROM sys.key_constraints cco
JOIN sys.index_columns cc ON cco.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id
JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
join sys.schemas s on cco.schema_id=s.schema_id and s.name=#schema
WHERE OBJECT_NAME(parent_object_id) = #TableName AND i.type = 2 AND is_primary_key = 0 AND is_unique_constraint = 1
'
print #sql
INSERT INTO #Uniques(ObjectID)
exec sp_executesql #sql,
N'#TableName varchar(50),#schema varchar(50)',
#TableName=#TableName,#schema=#schema
/*
SELECT DISTINCT PKObject = cco.object_id
FROM sys.key_constraints cco
JOIN sys.index_columns cc ON cco.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id
JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
WHERE OBJECT_NAME(parent_object_id) = #TableName AND i.type = 2 AND is_primary_key = 0 AND is_unique_constraint = 1
*/
SET #ClusteredPK = CASE WHEN ##ROWCOUNT > 0 THEN 1 ELSE 0 END
declare #t TableType
insert #t select * from #PKObjectID
declare #u TableType
insert #u select * from #Uniques
set #sql=
'
use '+#DBName+'
SELECT distinct '',CONSTRAINT '' + #NewTableName+''_''+replace(cco.name,#TableName,'''') + CASE type WHEN ''PK'' THEN '' PRIMARY KEY '' + CASE WHEN pk.ObjectID IS NULL THEN '' NONCLUSTERED '' ELSE '' CLUSTERED '' END WHEN ''UQ'' THEN '' UNIQUE '' END + CASE WHEN u.ObjectID IS NOT NULL THEN '' NONCLUSTERED '' ELSE '''' END
+ ''(''+REVERSE(SUBSTRING(REVERSE(( SELECT c.name + + CASE WHEN cc.is_descending_key = 1 THEN '' DESC'' ELSE '' ASC'' END + '',''
FROM sys.key_constraints ccok
LEFT JOIN sys.index_columns cc ON ccok.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id
LEFT JOIN sys.columns c ON cc.object_id = c.object_id AND cc.column_id = c.column_id
LEFT JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
WHERE i.object_id = ccok.parent_object_id AND ccok.object_id = cco.object_id
order by key_ordinal FOR XML PATH(''''))), 2, 8000)) + '')''
FROM sys.key_constraints cco
inner join sys.schemas s on cco.schema_id=s.schema_id and s.name=#schema
LEFT JOIN #U u ON cco.object_id = u.objectID
LEFT JOIN #t pk ON cco.object_id = pk.ObjectID
WHERE OBJECT_NAME(cco.parent_object_id) = #TableName
'
print #sql
INSERT INTO #Definition(FieldValue)
exec sp_executesql #sql,
N'#TableName varchar(50),#NewTableName varchar(50),#schema varchar(50),#t TableType readonly,#u TableType readonly',
#TableName=#TableName,#NewTableName=#NewTableName,#schema=#schema,#t=#t,#u=#u
/*
SELECT ',CONSTRAINT ' + name + CASE type WHEN 'PK' THEN ' PRIMARY KEY ' + CASE WHEN pk.ObjectID IS NULL THEN ' NONCLUSTERED ' ELSE ' CLUSTERED ' END WHEN 'UQ' THEN ' UNIQUE ' END + CASE WHEN u.ObjectID IS NOT NULL THEN ' NONCLUSTERED ' ELSE '' END
+ '(' +REVERSE(SUBSTRING(REVERSE(( SELECT c.name + + CASE WHEN cc.is_descending_key = 1 THEN ' DESC' ELSE ' ASC' END + ','
FROM sys.key_constraints ccok
LEFT JOIN sys.index_columns cc ON ccok.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id
LEFT JOIN sys.columns c ON cc.object_id = c.object_id AND cc.column_id = c.column_id
LEFT JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
WHERE i.object_id = ccok.parent_object_id AND ccok.object_id = cco.object_id FOR XML PATH(''))), 2, 8000)) + ')'
FROM sys.key_constraints cco
LEFT JOIN #PKObjectID pk ON cco.object_id = pk.ObjectID
LEFT JOIN #Uniques u ON cco.object_id = u.objectID
WHERE OBJECT_NAME(cco.parent_object_id) = #TableName
*/
END
INSERT INTO #Definition(FieldValue) VALUES(')')
set #sql=
'
use '+#DBName+'
select '' on '' + d.name + ''([''+c.name+''])''
from sys.tables t join sys.indexes i on(i.object_id = t.object_id and i.index_id < 2)
join sys.index_columns ic on(ic.partition_ordinal > 0 and ic.index_id = i.index_id and ic.object_id = t.object_id)
join sys.columns c on(c.object_id = ic.object_id and c.column_id = ic.column_id)
join sys.schemas s on t.schema_id=s.schema_id
join sys.data_spaces d on i.data_space_id=d.data_space_id
where t.name=#TableName and s.name=#schema
order by key_ordinal
'
print 'x'
print #sql
INSERT INTO #Definition(FieldValue)
exec sp_executesql #sql,
N'#TableName varchar(50),#schema varchar(50)',
#TableName=#TableName,#schema=#schema
IF #IncludeIndexes = 1
BEGIN
set #sql=
'
use '+#DBName+'
SELECT distinct '' CREATE '' + i.type_desc + '' INDEX ['' + replace(i.name COLLATE SQL_Latin1_General_CP1_CI_AS,#TableName,#NewTableName) + ''] ON '+#DBName+'.'+#NewTableSchema+'.'+#NewTableName+' (''
+ REVERSE(SUBSTRING(REVERSE(( SELECT name + CASE WHEN sc.is_descending_key = 1 THEN '' DESC'' ELSE '' ASC'' END + '',''
FROM sys.index_columns sc
JOIN sys.columns c ON sc.object_id = c.object_id AND sc.column_id = c.column_id
WHERE t.name=#TableName AND sc.object_id = i.object_id AND sc.index_id = i.index_id
and is_included_column=0
ORDER BY key_ordinal ASC FOR XML PATH('''') )), 2, 8000)) + '')''+
ISNULL( '' include (''+REVERSE(SUBSTRING(REVERSE(( SELECT name + '',''
FROM sys.index_columns sc
JOIN sys.columns c ON sc.object_id = c.object_id AND sc.column_id = c.column_id
WHERE t.name=#TableName AND sc.object_id = i.object_id AND sc.index_id = i.index_id
and is_included_column=1
ORDER BY key_ordinal ASC FOR XML PATH('''') )), 2, 8000))+'')'' ,'''')+''''
FROM sys.indexes i join sys.tables t on i.object_id=t.object_id
join sys.schemas s on t.schema_id=s.schema_id
AND CASE WHEN #ClusteredPK = 1 AND is_primary_key = 1 AND i.type = 1 THEN 0 ELSE 1 END = 1 AND is_unique_constraint = 0 AND is_primary_key = 0
where t.name=#TableName and s.name=#schema
'
print #sql
INSERT INTO #Definition(FieldValue)
exec sp_executesql #sql,
N'#TableName varchar(50),#NewTableName varchar(50),#schema varchar(50), #ClusteredPK bit',
#TableName=#TableName,#NewTableName=#NewTableName,#schema=#schema,#ClusteredPK=#ClusteredPK
END
/*
SELECT 'CREATE ' + type_desc + ' INDEX [' + [name] COLLATE SQL_Latin1_General_CP1_CI_AS + '] ON [' + OBJECT_NAME(object_id) + '] (' + REVERSE(SUBSTRING(REVERSE(( SELECT name + CASE WHEN sc.is_descending_key = 1 THEN ' DESC' ELSE ' ASC' END + ','
FROM sys.index_columns sc
JOIN sys.columns c ON sc.object_id = c.object_id AND sc.column_id = c.column_id
WHERE OBJECT_NAME(sc.object_id) = #TableName AND sc.object_id = i.object_id AND sc.index_id = i.index_id
ORDER BY index_column_id ASC FOR XML PATH('') )), 2, 8000)) + ')'
FROM sys.indexes i
WHERE OBJECT_NAME(object_id) = #TableName
AND CASE WHEN #ClusteredPK = 1 AND is_primary_key = 1 AND type = 1 THEN 0 ELSE 1 END = 1 AND is_unique_constraint = 0 AND is_primary_key = 0
*/
INSERT INTO #MainDefinition(FieldValue)
SELECT FieldValue FROM #Definition
ORDER BY DefinitionID ASC
----------------------------------
--SELECT FieldValue+'' FROM #MainDefinition FOR XML PATH('')
set #script='use '+#DBName+' '+(SELECT FieldValue+'' FROM #MainDefinition FOR XML PATH(''))
--declare #q varchar(max)
--set #q=(select replace((SELECT FieldValue FROM #MainDefinition FOR XML PATH('')),'</FieldValue>',''))
--set #script=(select REPLACE(#q,'<FieldValue>',''))
--drop type TableType
END try
-- ##############################################################################################################################################################################
BEGIN CATCH
BEGIN
-- INIZIO Procedura in errore =========================================================================================================================================================
PRINT '***********************************************************************************************************************************************************'
PRINT 'ErrorNumber : ' + CAST(ERROR_NUMBER() AS NVARCHAR(MAX))
PRINT 'ErrorSeverity : ' + CAST(ERROR_SEVERITY() AS NVARCHAR(MAX))
PRINT 'ErrorState : ' + CAST(ERROR_STATE() AS NVARCHAR(MAX))
PRINT 'ErrorLine : ' + CAST(ERROR_LINE() AS NVARCHAR(MAX))
PRINT 'ErrorMessage : ' + CAST(ERROR_MESSAGE() AS NVARCHAR(MAX))
PRINT '***********************************************************************************************************************************************************'
-- FINE Procedura in errore =========================================================================================================================================================
END
set #script=''
return -1
END CATCH
-- ##############################################################################################################################################################################
to exec it:
declare #s varchar(max)
exec [util_ScriptTable] 'db','schema_source','table_source',1,1,'schema_dest','tab_dest',0,#s output
select #s

Related

The operation failed because an index or statistics with name {Index name }already exists on table

When Running the below script to create indexes on Table from another it fails trying to re-create the same index. Error "The operation failed because an index or statistics with already exists on table". Here is the code. Pls let me know if you have any questions
DECLARE
#schema sysname
,#TableName varchar(255)
,#IncludeIndexes BIT
,#NewTableName varchar(255)
SET #TableName = 'SourceTableNameHere'
SET #NewTableName ='TargetTableNameHere'
SET #IncludeIndexes = 1
set #schema = 'dbo'
IF #IncludeIndexes = 1
BEGIN
DECLARE #IndexId int, #IndexName nvarchar(255), #IsUnique bit, #IsUniqueConstraint bit, #FilterDefinition nvarchar(max),#IndexType int,#IndexColumnID int
DECLARE indexcursor CURSOR FOR
select distinct sc.index_id,i.name, is_unique, is_unique_constraint, filter_definition,i.type,index_column_id
FROM sys.index_columns sc
JOIN sys.columns c ON sc.object_id = c.object_id AND sc.column_id = c.column_id
LEFT JOIN sys.indexes i on sc.object_id = i.object_id AND sc.index_id = i.index_id
WHERE OBJECT_NAME(sc.object_id) = #TableName AND sc.object_id = i.object_id AND sc.index_id = i.index_id
ORDER BY index_column_id ASC
OPEN indexcursor;
WHILE 1 = 1
BEGIN
FETCH NEXT FROM indexcursor INTO #IndexId, #IndexName, #IsUnique, #IsUniqueConstraint, #FilterDefinition, #IndexType,#IndexColumnID ;
IF ##fetch_status <> 0
BREAK
-- WHILE ##FETCH_STATUS = 0
--BEGIN
DECLARE #Unique nvarchar(255)
SET #Unique = CASE WHEN #IsUnique = 1 THEN ' UNIQUE ' ELSE '' END
DECLARE #KeyColumns nvarchar(max), #IncludedColumns nvarchar(max)
SET #KeyColumns = ''
SET #IncludedColumns = ''
select #KeyColumns = #KeyColumns + '[' + c.name + '] ' + CASE WHEN is_descending_key = 1 THEN 'DESC' ELSE 'ASC' END + ',' from sys.index_columns ic
inner join sys.columns c ON c.object_id = ic.object_id and c.column_id = ic.column_id
where index_id = #IndexId and ic.object_id = object_id('[' + #schema + '].[' + #TableName + ']') and key_ordinal > 0
order by index_column_id
select #IncludedColumns = #IncludedColumns + '[' + c.name + '],' from sys.index_columns ic
inner join sys.columns c ON c.object_id = ic.object_id and c.column_id = ic.column_id
where index_id = #IndexId and ic.object_id = object_id('[' + #schema + '].[' + #TableName + ']') and key_ordinal = 0
order by index_column_id
IF LEN(#KeyColumns) > 0
SET #KeyColumns = LEFT(#KeyColumns, LEN(#KeyColumns) - 1)
IF LEN(#IncludedColumns) > 0
BEGIN
SET #IncludedColumns = ' INCLUDE (' + LEFT(#IncludedColumns, LEN(#IncludedColumns) - 1) + ')'
END
IF #FilterDefinition IS NULL
SET #FilterDefinition = ''
ELSE
SET #FilterDefinition = 'WHERE ' + #FilterDefinition + ' '
SET #IndexName = Replace(#IndexName,#TableName,#NewTableName)
/* IF #IndexType = 1 -- Clustered
BEGIN exec('CREATE ' + #Unique + ' CLUSTERED INDEX [' + #IndexName + '] ON [' + #schema + '].[' + #NewTableName + '] (' + #KeyColumns + ')' + #IncludedColumns + #FilterDefinition)
END */
IF #IndexType = 2 --Nonclustered
BEGIN exec('CREATE ' + #Unique + ' NONCLUSTERED INDEX [' + #IndexName + '] ON [' + #schema + '].[' + #NewTableName + '] (' + #KeyColumns + ')' + #IncludedColumns + #FilterDefinition)
END
/* IF #IsUniqueConstraint =1
BEGIN
SET #IndexName = REPLACE(#IndexName, #TableName, #NewTableName)
exec('ALTER TABLE [' + #schema + '].[' + #NewTableName + '] ADD CONSTRAINT [' + #IndexName + '] UNIQUE NONCLUSTERED (' + #KeyColumns + ')');
END
*/
FETCH NEXT FROM indexcursor INTO #IndexId, #IndexName, #IsUnique, #IsUniqueConstraint, #FilterDefinition,#IndexType,#IndexColumnID;
END;
CLOSE indexcursor;
DEALLOCATE indexcursor;
END
Not sure what to try next.to solve the issue

How to get index names for all databases by database name on a SQL Server

The title pretty much sums up what I am looking for. So I am looking to get some meta information for sql indexes for eg. TableName, SchemaName, DatabaseName.
SELECT
TableName = t.name,
IndexName = ind.name,
IndexId = ind.index_id,
ColumnId = ic.index_column_id,
ColumnName = col.name,
SchemaName = s.name
FROM
sys.indexes ind
INNER JOIN
sys.index_columns ic ON ind.object_id = ic.object_id and ind.index_id = ic.index_id
INNER JOIN
sys.columns col ON ic.object_id = col.object_id and ic.column_id = col.column_id
INNER JOIN
sys.tables t ON ind.object_id = t.object_id
INNER JOIN
sys.schemas s ON t.schema_id = s.schema_id
WHERE
ind.name = 'testindex'
ORDER BY
t.name, ind.name, ind.index_id, ic.index_column_id;
So far I have managed to get TableName and SchemaName for an index, however I don't know how to get the database name.
Using Aaron Bertrand's script for making a more reliable and flexible sp_MSforeachdb, you can use your query with a modification.
You will need to use this, or a cursor, or some other method to iterate over all databases on your server. This is one of the bests I have seen, since Microsoft's version can skip databases as Aaron points out.
sp_foreachdb Method
CREATE PROCEDURE dbo.sp_foreachdb
#command NVARCHAR(MAX),
#replace_character NCHAR(1) = N'?',
#print_dbname BIT = 0,
#print_command_only BIT = 0,
#suppress_quotename BIT = 0,
#system_only BIT = NULL,
#user_only BIT = NULL,
#name_pattern NVARCHAR(300) = N'%',
#database_list NVARCHAR(MAX) = NULL,
#recovery_model_desc NVARCHAR(120) = NULL,
#compatibility_level TINYINT = NULL,
#state_desc NVARCHAR(120) = N'ONLINE',
#is_read_only BIT = 0,
#is_auto_close_on BIT = NULL,
#is_auto_shrink_on BIT = NULL,
#is_broker_enabled BIT = NULL
AS
BEGIN
SET NOCOUNT ON;
DECLARE
#sql NVARCHAR(MAX),
#dblist NVARCHAR(MAX),
#db NVARCHAR(300),
#i INT;
IF #database_list > N''
BEGIN
;WITH n(n) AS
(
SELECT ROW_NUMBER() OVER (ORDER BY s1.name) - 1
FROM sys.objects AS s1
CROSS JOIN sys.objects AS s2
)
SELECT #dblist = REPLACE(REPLACE(REPLACE(x,'</x><x>',','),
'</x>',''),'<x>','')
FROM
(
SELECT DISTINCT x = 'N''' + LTRIM(RTRIM(SUBSTRING(
#database_list, n,
CHARINDEX(',', #database_list + ',', n) - n))) + ''''
FROM n WHERE n <= LEN(#database_list)
AND SUBSTRING(',' + #database_list, n, 1) = ','
FOR XML PATH('')
) AS y(x);
END
CREATE TABLE #x(db NVARCHAR(300));
SET #sql = N'SELECT name FROM sys.databases WHERE 1=1'
+ CASE WHEN #system_only = 1 THEN
' AND database_id IN (1,2,3,4)'
ELSE '' END
+ CASE WHEN #user_only = 1 THEN
' AND database_id NOT IN (1,2,3,4)'
ELSE '' END
+ CASE WHEN #name_pattern <> N'%' THEN
' AND name LIKE N''%' + REPLACE(#name_pattern, '''', '''''') + '%'''
ELSE '' END
+ CASE WHEN #dblist IS NOT NULL THEN
' AND name IN (' + #dblist + ')'
ELSE '' END
+ CASE WHEN #recovery_model_desc IS NOT NULL THEN
' AND recovery_model_desc = N''' + #recovery_model_desc + ''''
ELSE '' END
+ CASE WHEN #compatibility_level IS NOT NULL THEN
' AND compatibility_level = ' + RTRIM(#compatibility_level)
ELSE '' END
+ CASE WHEN #state_desc IS NOT NULL THEN
' AND state_desc = N''' + #state_desc + ''''
ELSE '' END
+ CASE WHEN #is_read_only IS NOT NULL THEN
' AND is_read_only = ' + RTRIM(#is_read_only)
ELSE '' END
+ CASE WHEN #is_auto_close_on IS NOT NULL THEN
' AND is_auto_close_on = ' + RTRIM(#is_auto_close_on)
ELSE '' END
+ CASE WHEN #is_auto_shrink_on IS NOT NULL THEN
' AND is_auto_shrink_on = ' + RTRIM(#is_auto_shrink_on)
ELSE '' END
+ CASE WHEN #is_broker_enabled IS NOT NULL THEN
' AND is_broker_enabled = ' + RTRIM(#is_broker_enabled)
ELSE '' END;
INSERT #x EXEC sp_executesql #sql;
DECLARE c CURSOR
LOCAL FORWARD_ONLY STATIC READ_ONLY
FOR SELECT CASE WHEN #suppress_quotename = 1 THEN
db
ELSE
QUOTENAME(db)
END
FROM #x ORDER BY db;
OPEN c;
FETCH NEXT FROM c INTO #db;
WHILE ##FETCH_STATUS = 0
BEGIN
SET #sql = REPLACE(#command, #replace_character, #db);
IF #print_command_only = 1
BEGIN
PRINT '/* For ' + #db + ': */'
+ CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10)
+ #sql
+ CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10);
END
ELSE
BEGIN
IF #print_dbname = 1
BEGIN
PRINT '/* ' + #db + ' */';
END
EXEC sp_executesql #sql;
END
FETCH NEXT FROM c INTO #db;
END
CLOSE c;
DEALLOCATE c;
END
Execution of Proc
EXEC sp_foreachdb
#command = 'SELECT
DBNAME = ''?'',
TableName = t.name,
IndexName = ind.name,
IndexId = ind.index_id,
ColumnId = ic.index_column_id,
ColumnName = col.name,
SchemaName = s.name
FROM
?.sys.indexes ind
INNER JOIN
?.sys.index_columns ic ON ind.object_id = ic.object_id and ind.index_id = ic.index_id
INNER JOIN
?.sys.columns col ON ic.object_id = col.object_id and ic.column_id = col.column_id
INNER JOIN
?.sys.tables t ON ind.object_id = t.object_id
INNER JOIN
?.sys.schemas s ON t.schema_id = s.schema_id
ORDER BY
t.name, ind.name, ind.index_id, ic.index_column_id'
,#print_command_only = 0
No Proc & No Cursor Method
Thanks to Sean Lange for reminding me how, you can use a hack of variable concatenation to not use a cursor, or a procedure, and accomplish the same task.
declare #sql varchar(max) = ''
select #sql = #sql
+ 'use '
+ quotename(name)
+ char(13)
+ 'select DBNAME = '''
+ name
+ ''',
TableName = t.name,
IndexName = ind.name,
IndexId = ind.index_id,
ColumnId = ic.index_column_id,
ColumnName = col.name,
SchemaName = s.name
FROM
sys.indexes ind
INNER JOIN
sys.index_columns ic ON ind.object_id = ic.object_id and ind.index_id = ic.index_id
INNER JOIN
sys.columns col ON ic.object_id = col.object_id and ic.column_id = col.column_id
INNER JOIN
sys.tables t ON ind.object_id = t.object_id
INNER JOIN
sys.schemas s ON t.schema_id = s.schema_id; '
+ char(13)
from sys.databases
where state = 0
exec(#sql)
I use something like this.
select t.name, i.name, t.object_id,
STUFF((
select N' , ' + name
from sys.columns c
join sys.index_columns ic on ic.object_id = c.object_id and ic.column_id = c.column_id
where ic.object_id = i.object_id and c.object_id = i.object_id
and ic.index_id = i.index_id
and ic.is_included_column=0
order by ic.is_included_column, ic.key_ordinal
FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N''
) IndexKeyColumns
,
STUFF((
select N' , ' + name
from sys.columns c
join sys.index_columns ic on ic.object_id = c.object_id and ic.column_id = c.column_id
where ic.object_id = i.object_id and c.object_id = i.object_id
and ic.index_id = i.index_id
and ic.is_included_column=1
order by ic.is_included_column, ic.key_ordinal
FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N''
) IncludedColumns
from sys.indexes i
join sys.tables t on t.object_id = i.object_id
where i.type in (1,2)
and i.is_primary_key = 0
order by t.name, i.name
You can execute against your dbs with dynamic sql
declare myDatabases cursor for
select name from sys.databases
where name in ('db1','db2') -- leave this out for all of them
order by name
declare #tempDBName varchar(200)
open myDatabases
fetch next from mydatabases into #tempDBName
while ##FETCH_STATUS = 0
begin
declare #sql nvarchar(max)
set #sql = N'
declare #innersql nvarchar(max) = ''use ''+#tempDBName
set #innersql = #innersql +''
select db_name()
''
exec (#innersql)
'
exec sp_executesql #sql,N'#tempDBName varchar(200)',#tempDBName
fetch next from myDatabases into #tempDBName
end
close myDatabases
deallocate myDatabases
Putting it together with your query, rather than mine (many quotes to sort out) it would be something like this... pull out the where clause line entirely should get you your selection
declare myDatabases cursor for
select name from sys.databases
where name in ('db1','db2')
order by name
declare #tempDBName varchar(200)
open myDatabases
fetch next from mydatabases into #tempDBName
while ##FETCH_STATUS = 0
begin
declare #sql nvarchar(max)
set #sql = N'
declare #innersql nvarchar(max) = ''use ''+#tempDBName
set #innersql = #innersql +
'''
+
--select db_name()
'
SELECT
TableName = t.name,
IndexName = ind.name,
IndexId = ind.index_id,
ColumnId = ic.index_column_id,
ColumnName = col.name,
SchemaName = s.name
FROM
sys.indexes ind
INNER JOIN
sys.index_columns ic ON ind.object_id = ic.object_id and ind.index_id = ic.index_id
INNER JOIN
sys.columns col ON ic.object_id = col.object_id and ic.column_id = col.column_id
INNER JOIN
sys.tables t ON ind.object_id = t.object_id
INNER JOIN
sys.schemas s ON t.schema_id = s.schema_id
WHERE
ind.name = ''''testindex''''
ORDER BY
t.name, ind.name, ind.index_id, ic.index_column_id;
'
+
'''
exec (#innersql)
'
exec sp_executesql #sql,N'#tempDBName varchar(200)',#tempDBName
fetch next from myDatabases into #tempDBName
end
close myDatabases
deallocate myDatabases

Remove Identity Setting from all Tables which have Identity

Using SQL Server, to remove the is identity setting (auto increment) for a table, I have to drop and recreate a table.
Is there a way to disable the Idendity Setting for all tables with a simple script?
You cannot remove an IDENTITY specification once set.
I assume that you are using SQL SERVER:
You have to use dynamic SQL query to drop all Identity Columns:
DECLARE #SQL as varchar(8000)
SET #SQL = ''
select #SQL = #SQL + 'ALTER TABLE [' + [TABLE_SCHEMA] + '].[' + [TABLE_NAME] + '] DROP COLUMN [' + [COLUMN_NAME] + '] ; '
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
ORDER BY TABLE_NAME
EXEC( #SQL)
Note: COLUMNPROPERTY is starting with SQL SERVER 2008
UPDATE1 :
According to your comment the following query
loop over Tables
Check if table contains Identity column.
If True, It Check if table has Relations
If False, it check if it contains Data
If not containing Data it drop table and recreate it without Identity.
Note: Query contains a lot of code because generating create table script
DECLARE #strSchema as varchar(50)
DECLARE #strName as varchar(50)
DECLARE #strQuery as varchar(8000)
DECLARE csrCursor Cursor For SELECT [TABLE_SCHEMA],[TABLE_NAME] FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
ORDER BY TABLE_NAME
OPEN csrCursor
FETCH NEXT FROM csrCursor INTO #strSchema,#strName
WHILE ##FETCH_STATUS <> -1
BEGIN
IF NOT EXISTS(SELECT
name, OBJECT_NAME(parent_object_id) 'Table'
FROM
sys.foreign_keys
WHERE
referenced_object_id = OBJECT_ID('[' + #strSchema + '].[' + #strName + ']'))
BEGIN
SET #strQuery = 'IF NOT EXISTS(SELECT * FROM [' + #strSchema + '].[' + #strName + '])
BEGIN
DROP TABLE [' + #strSchema + '].[' + #strName + '];
'
DECLARE #table_name SYSNAME
SELECT #table_name = #strSchema + '.' + #strName
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
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)')
), '')
SET #strQuery = #strQuery + #SQL + '
END'
--PRINT(#strQuery)
EXEC (#strQuery)
END
FETCH NEXT FROM csrCursor INTO #strSchema,#strName
END
Close csrCursor
DEALLOCATE csrCursor
Query is tested under SQL Server 2016 and it works fine

How to copy a table schema and constraints to a table of different database? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
What SQL can be used to copy the schema of a specified table to a table in different database?
Sure its 2 years later, but wanted to contribute a solution. This procedure copies a table into "BackUp_<YYYYMMDD>_<Original Table Name> and its Primary Key Constraint. It surrounds the table name with wildcard '%' in order to allow copying of a group of tables. I'm only moving the primary key because there is no reliance on other tables, therefore less headaches. Also, No Cursors!
ALTER PROCEDURE dbo.Admin_CopyTable
#TableName NVARCHAR(255)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from interfering with SELECT statements.
SET NOCOUNT ON;
-- is there any work to do?
IF NOT (isNull(#TableName,'')='')
BEGIN
-- Get list of all tables that match the #TableName wildcard
DECLARE #tables TABLE (id BIGINT IDENTITY(1,1), [name] NVARCHAR(255)) -- using id as means to avoid cursor
INSERT INTO #tables SELECT table_name FROM information_schema.tables WHERE table_name LIKE '%' + #TableName + '%' AND table_name NOT LIKE 'BackUp_%' ORDER BY table_name
-- Go through each table and copy it
DECLARE #row BIGINT;
DECLARE #thisTable AS NVARCHAR(255);
DECLARE #dSQL NVARCHAR(4000); -- holds the SQL string to execute and copy table data
DECLARE #TablePrefix NVARCHAR(255); -- Name that is prepended before the name of the actual table to show it is a backup table
-- set default prefix by adding todays date to the table name
SELECT #TablePrefix = 'BackUp_' + CONVERT(NVARCHAR(10), GetDate(), 112) + '_'; -- Date as YYYYMMDD
-- Get first row for looping through list of tables
SELECT #row = MIN(id) FROM #tables;
WHILE (isNull(#row, 0) <> 0) -- returns null when no more rows, which gets converted to 0 (zero)
BEGIN
SELECT #thisTable = [name] FROM #tables where id = #row
IF NOT EXISTS(SELECT table_name FROM information_schema.tables WHERE table_name like #TablePrefix + #thisTable)
BEGIN
SET #dSQL = 'Select * Into ' + #TablePrefix + #thisTable + ' from ' + #thisTable;
EXEC (#dSQL)
PRINT #TablePrefix + #thisTable + ': Data Backed up.'
-- Copy the Primary Key into the Backup table
BEGIN
-- Get list of all the columns that make up the Primary Key
-- for composite PK's = one row per pk column
DECLARE #PKColsTbl table ([name] NVARCHAR(255), col NVARCHAR(255))
INSERT INTO #PKColsTbl
SELECT c.Constraint_Name, c.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk
,INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
WHERE pk.TABLE_NAME = #thisTable
and CONSTRAINT_TYPE = 'PRIMARY KEY'
and c.TABLE_NAME = pk.TABLE_NAME
and c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME
-- Transpose rows into one column as a comma delimeted string
DECLARE #pkCol NVARCHAR(255);
SELECT #pkCol = stuff((select ',' + col from #PKColsTbl for XML PATH('')), 1,1,'')
-- Build the dynamic SQL statement and execute it
SET #dSQL = 'ALTER TABLE ' + #TablePrefix + #thisTable + ' ADD CONSTRAINT ' + 'PK_' + #TablePrefix + #thisTable + ' PRIMARY KEY (' + #pkCol + ')'
EXEC (#dSQL)
PRINT #TablePrefix + #thisTable + ': PK Created.'
-- Since its a loop, clear out the table
DELETE FROM #PKColsTbl
END
-- END of Copying the Primary Key
END
ELSE
BEGIN
PRINT #TablePrefix + #thisTable + ': Exists!'
END
-- Get next row
SELECT #row = min(id) FROM #tables WHERE id > #row
END
END
END
SELECT INTO will create a new table with the same schema. So you could:
SELECT *
INTO newdb.dbo.newtable
FROM olddb.dbo.oldtable
To just copy the schema and not the data:
SELECT TOP 0 *
INTO newdb.dbo.newtable
FROM olddb.dbo.oldtable
This would not copy indexes or keys. To copy those, right click the table in SQL Sever Management Studio and choose 'Script table as'. That will give you a script you can run on the new database.
Try with SQL SERVER SCRIPT WIZARD
1) Select a database
2) Right Click - > Tasks - > Generate scripts
3) Click Next - > and in the Select Database Screen, choose the table(will be selected by default). Check the "Script All Objects In The Selected Database" .
4) Click Finish.
Hope this helps
i wrote this sp to create automatically the schema with all things, pk, fk, partitions, constraints...
IMPORTANT!!
before exec
create type TestTableType as table (ObjectID int)
here the SP:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--*************************************************************************************************'
-- La procedura crea lo script di una tabella
--*************************************************************************************************'
alter PROCEDURE [dbo].[util_ScriptTable]
#DBName SYSNAME
,#schema sysname
,#TableName SYSNAME
,#IncludeConstraints BIT = 1
,#IncludeIndexes BIT = 1
,#NewTableSchema sysname
,#NewTableName SYSNAME = NULL
,#UseSystemDataTypes BIT = 0
,#script varchar(max) output
AS
BEGIN try
if not exists (select * from sys.types where name = 'TestTableType')
create type TestTableType as table (ObjectID int)--drop type TestTableType
declare #sql nvarchar(max)
DECLARE #MainDefinition TABLE (FieldValue VARCHAR(200))
--DECLARE #DBName SYSNAME
DECLARE #ClusteredPK BIT
DECLARE #TableSchema NVARCHAR(255)
--SET #DBName = DB_NAME(DB_ID())
SELECT #TableName = name FROM sysobjects WHERE id = OBJECT_ID(#TableName)
DECLARE #ShowFields TABLE (FieldID INT IDENTITY(1,1)
,DatabaseName VARCHAR(100)
,TableOwner VARCHAR(100)
,TableName VARCHAR(100)
,FieldName VARCHAR(100)
,ColumnPosition INT
,ColumnDefaultValue VARCHAR(100)
,ColumnDefaultName VARCHAR(100)
,IsNullable BIT
,DataType VARCHAR(100)
,MaxLength varchar(10)
,NumericPrecision INT
,NumericScale INT
,DomainName VARCHAR(100)
,FieldListingName VARCHAR(110)
,FieldDefinition CHAR(1)
,IdentityColumn BIT
,IdentitySeed INT
,IdentityIncrement INT
,IsCharColumn BIT
,IsComputed varchar(255))
DECLARE #HoldingArea TABLE(FldID SMALLINT IDENTITY(1,1)
,Flds VARCHAR(4000)
,FldValue CHAR(1) DEFAULT(0))
DECLARE #PKObjectID TABLE(ObjectID INT)
DECLARE #Uniques TABLE(ObjectID INT)
DECLARE #HoldingAreaValues TABLE(FldID SMALLINT IDENTITY(1,1)
,Flds VARCHAR(4000)
,FldValue CHAR(1) DEFAULT(0))
DECLARE #Definition TABLE(DefinitionID SMALLINT IDENTITY(1,1)
,FieldValue VARCHAR(200))
set #sql=
'
use '+#DBName+'
SELECT distinct DB_NAME()
,TABLE_SCHEMA
,TABLE_NAME
,''[''+COLUMN_NAME+'']'' as COLUMN_NAME
,CAST(ORDINAL_POSITION AS INT)
,COLUMN_DEFAULT
,dobj.name AS ColumnDefaultName
,CASE WHEN c.IS_NULLABLE = ''YES'' THEN 1 ELSE 0 END
,DATA_TYPE
,case CHARACTER_MAXIMUM_LENGTH when -1 then ''max'' else CAST(CHARACTER_MAXIMUM_LENGTH AS varchar) end--CAST(CHARACTER_MAXIMUM_LENGTH AS INT)
,CAST(NUMERIC_PRECISION AS INT)
,CAST(NUMERIC_SCALE AS INT)
,DOMAIN_NAME
,COLUMN_NAME + '',''
,'''' AS FieldDefinition
,CASE WHEN ic.object_id IS NULL THEN 0 ELSE 1 END AS IdentityColumn
,CAST(ISNULL(ic.seed_value,0) AS INT) AS IdentitySeed
,CAST(ISNULL(ic.increment_value,0) AS INT) AS IdentityIncrement
,CASE WHEN st.collation_name IS NOT NULL THEN 1 ELSE 0 END AS IsCharColumn
,cc.definition
FROM INFORMATION_SCHEMA.COLUMNS c
JOIN sys.columns sc ON c.TABLE_NAME = OBJECT_NAME(sc.object_id) AND c.COLUMN_NAME = sc.Name
LEFT JOIN sys.identity_columns ic ON c.TABLE_NAME = OBJECT_NAME(ic.object_id) AND c.COLUMN_NAME = ic.Name
JOIN sys.types st ON COALESCE(c.DOMAIN_NAME,c.DATA_TYPE) = st.name
LEFT OUTER JOIN sys.objects dobj ON dobj.object_id = sc.default_object_id AND dobj.type = ''D''
left join sys.computed_columns cc on c.TABLE_NAME=OBJECT_NAME(cc.object_id) and sc.column_id=cc.column_id
WHERE c.TABLE_NAME = #TableName and c.TABLE_SCHEMA=#schema
ORDER BY c.TABLE_NAME, c.ORDINAL_POSITION
'
print #sql
INSERT INTO #ShowFields( DatabaseName
,TableOwner
,TableName
,FieldName
,ColumnPosition
,ColumnDefaultValue
,ColumnDefaultName
,IsNullable
,DataType
,MaxLength
,NumericPrecision
,NumericScale
,DomainName
,FieldListingName
,FieldDefinition
,IdentityColumn
,IdentitySeed
,IdentityIncrement
,IsCharColumn
,IsComputed)
exec sp_executesql #sql,
N'#TableName varchar(50),#schema varchar(50)',
#TableName=#TableName,#schema=#schema
/*
SELECT #DBName--DB_NAME()
,TABLE_SCHEMA
,TABLE_NAME
,COLUMN_NAME
,CAST(ORDINAL_POSITION AS INT)
,COLUMN_DEFAULT
,dobj.name AS ColumnDefaultName
,CASE WHEN c.IS_NULLABLE = 'YES' THEN 1 ELSE 0 END
,DATA_TYPE
,CAST(CHARACTER_MAXIMUM_LENGTH AS INT)
,CAST(NUMERIC_PRECISION AS INT)
,CAST(NUMERIC_SCALE AS INT)
,DOMAIN_NAME
,COLUMN_NAME + ','
,'' AS FieldDefinition
,CASE WHEN ic.object_id IS NULL THEN 0 ELSE 1 END AS IdentityColumn
,CAST(ISNULL(ic.seed_value,0) AS INT) AS IdentitySeed
,CAST(ISNULL(ic.increment_value,0) AS INT) AS IdentityIncrement
,CASE WHEN st.collation_name IS NOT NULL THEN 1 ELSE 0 END AS IsCharColumn
FROM INFORMATION_SCHEMA.COLUMNS c
JOIN sys.columns sc ON c.TABLE_NAME = OBJECT_NAME(sc.object_id) AND c.COLUMN_NAME = sc.Name
LEFT JOIN sys.identity_columns ic ON c.TABLE_NAME = OBJECT_NAME(ic.object_id) AND c.COLUMN_NAME = ic.Name
JOIN sys.types st ON COALESCE(c.DOMAIN_NAME,c.DATA_TYPE) = st.name
LEFT OUTER JOIN sys.objects dobj ON dobj.object_id = sc.default_object_id AND dobj.type = 'D'
WHERE c.TABLE_NAME = #TableName
ORDER BY c.TABLE_NAME, c.ORDINAL_POSITION
*/
SELECT TOP 1 #TableSchema = TableOwner FROM #ShowFields
INSERT INTO #HoldingArea (Flds) VALUES('(')
INSERT INTO #Definition(FieldValue)VALUES('CREATE TABLE ' + CASE WHEN #NewTableName IS NOT NULL THEN #DBName + '.' + #NewTableSchema + '.' + #NewTableName ELSE #DBName + '.' + #TableSchema + '.' + #TableName END)
INSERT INTO #Definition(FieldValue)VALUES('(')
INSERT INTO #Definition(FieldValue)
SELECT CHAR(10) + FieldName + ' ' +
--CASE WHEN DomainName IS NOT NULL AND #UseSystemDataTypes = 0 THEN DomainName + CASE WHEN IsNullable = 1 THEN ' NULL ' ELSE ' NOT NULL ' END ELSE UPPER(DataType) +CASE WHEN IsCharColumn = 1 THEN '(' + CAST(MaxLength AS VARCHAR(10)) + ')' ELSE '' END +CASE WHEN IdentityColumn = 1 THEN ' IDENTITY(' + CAST(IdentitySeed AS VARCHAR(5))+ ',' + CAST(IdentityIncrement AS VARCHAR(5)) + ')' ELSE '' END +CASE WHEN IsNullable = 1 THEN ' NULL ' ELSE ' NOT NULL ' END +CASE WHEN ColumnDefaultName IS NOT NULL AND #IncludeConstraints = 1 THEN 'CONSTRAINT [' + ColumnDefaultName + '] DEFAULT' + UPPER(ColumnDefaultValue) ELSE '' END END + CASE WHEN FieldID = (SELECT MAX(FieldID) FROM #ShowFields) THEN '' ELSE ',' END
CASE WHEN DomainName IS NOT NULL AND #UseSystemDataTypes = 0 THEN DomainName +
CASe WHEN IsNullable = 1 THEN ' NULL '
ELSE ' NOT NULL '
END
ELSE
case when IsComputed is null then
UPPER(DataType) +
CASE WHEN IsCharColumn = 1 THEN '(' + CAST(MaxLength AS VARCHAR(10)) + ')'
ELSE
CASE WHEN DataType = 'numeric' THEN '(' + CAST(NumericPrecision AS VARCHAR(10))+','+ CAST(NumericScale AS VARCHAR(10)) + ')'
ELSE
CASE WHEN DataType = 'decimal' THEN '(' + CAST(NumericPrecision AS VARCHAR(10))+','+ CAST(NumericScale AS VARCHAR(10)) + ')'
ELSE ''
end
end
END +
CASE WHEN IdentityColumn = 1 THEN ' IDENTITY(' + CAST(IdentitySeed AS VARCHAR(5))+ ',' + CAST(IdentityIncrement AS VARCHAR(5)) + ')'
ELSE ''
END +
CASE WHEN IsNullable = 1 THEN ' NULL '
ELSE ' NOT NULL '
END +
CASE WHEN ColumnDefaultName IS NOT NULL AND #IncludeConstraints = 1 THEN 'CONSTRAINT [' + replace(ColumnDefaultName,#TableName,#NewTableName) + '] DEFAULT' + UPPER(ColumnDefaultValue)
ELSE ''
END
else
' as '+IsComputed+' '
end
END +
CASE WHEN FieldID = (SELECT MAX(FieldID) FROM #ShowFields) THEN ''
ELSE ','
END
FROM #ShowFields
IF #IncludeConstraints = 1
BEGIN
set #sql=
'
use '+#DBName+'
SELECT distinct '',CONSTRAINT ['' + replace(name,#TableName,#NewTableName) + ''] FOREIGN KEY ('' + ParentColumns + '') REFERENCES ['' + ReferencedObject + '']('' + ReferencedColumns + '')''
FROM ( SELECT ReferencedObject = OBJECT_NAME(fk.referenced_object_id), ParentObject = OBJECT_NAME(parent_object_id),fk.name
, REVERSE(SUBSTRING(REVERSE(( SELECT cp.name + '',''
FROM sys.foreign_key_columns fkc
JOIN sys.columns cp ON fkc.parent_object_id = cp.object_id AND fkc.parent_column_id = cp.column_id
WHERE fkc.constraint_object_id = fk.object_id FOR XML PATH('''') )), 2, 8000)) ParentColumns,
REVERSE(SUBSTRING(REVERSE(( SELECT cr.name + '',''
FROM sys.foreign_key_columns fkc
JOIN sys.columns cr ON fkc.referenced_object_id = cr.object_id AND fkc.referenced_column_id = cr.column_id
WHERE fkc.constraint_object_id = fk.object_id FOR XML PATH('''') )), 2, 8000)) ReferencedColumns
FROM sys.foreign_keys fk
inner join sys.schemas s on fk.schema_id=s.schema_id and s.name=#schema) a
WHERE ParentObject = #TableName
'
print #sql
INSERT INTO #Definition(FieldValue)
exec sp_executesql #sql,
N'#TableName varchar(50),#NewTableName varchar(50),#schema varchar(50)',
#TableName=#TableName,#NewTableName=#NewTableName,#schema=#schema
/*
SELECT ',CONSTRAINT [' + name + '] FOREIGN KEY (' + ParentColumns + ') REFERENCES [' + ReferencedObject + '](' + ReferencedColumns + ')'
FROM ( SELECT ReferencedObject = OBJECT_NAME(fk.referenced_object_id), ParentObject = OBJECT_NAME(parent_object_id),fk.name
, REVERSE(SUBSTRING(REVERSE(( SELECT cp.name + ','
FROM sys.foreign_key_columns fkc
JOIN sys.columns cp ON fkc.parent_object_id = cp.object_id AND fkc.parent_column_id = cp.column_id
WHERE fkc.constraint_object_id = fk.object_id FOR XML PATH('') )), 2, 8000)) ParentColumns,
REVERSE(SUBSTRING(REVERSE(( SELECT cr.name + ','
FROM sys.foreign_key_columns fkc
JOIN sys.columns cr ON fkc.referenced_object_id = cr.object_id AND fkc.referenced_column_id = cr.column_id
WHERE fkc.constraint_object_id = fk.object_id FOR XML PATH('') )), 2, 8000)) ReferencedColumns
FROM sys.foreign_keys fk ) a
WHERE ParentObject = #TableName
*/
set #sql=
'
use '+#DBName+'
SELECT distinct '',CONSTRAINT ['' + replace(c.name,#TableName,#NewTableName) + ''] CHECK '' + definition
FROM sys.check_constraints c join sys.schemas s on c.schema_id=s.schema_id and s.name=#schema
WHERE OBJECT_NAME(parent_object_id) = #TableName
'
print #sql
INSERT INTO #Definition(FieldValue)
exec sp_executesql #sql,
N'#TableName varchar(50),#NewTableName varchar(50),#schema varchar(50)',
#TableName=#TableName,#NewTableName=#NewTableName,#schema=#schema
/*
SELECT ',CONSTRAINT [' + name + '] CHECK ' + definition FROM sys.check_constraints
WHERE OBJECT_NAME(parent_object_id) = #TableName
*/
set #sql=
'
use '+#DBName+'
SELECT DISTINCT PKObject = cco.object_id
FROM sys.key_constraints cco
JOIN sys.index_columns cc ON cco.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id
JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
join sys.schemas s on cco.schema_id=s.schema_id and s.name=#schema
WHERE OBJECT_NAME(parent_object_id) = #TableName AND i.type = 1 AND is_primary_key = 1
'
print #sql
INSERT INTO #PKObjectID(ObjectID)
exec sp_executesql #sql,
N'#TableName varchar(50),#schema varchar(50)',
#TableName=#TableName,#schema=#schema
/*
SELECT DISTINCT PKObject = cco.object_id
FROM sys.key_constraints cco
JOIN sys.index_columns cc ON cco.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id
JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
WHERE OBJECT_NAME(parent_object_id) = #TableName AND i.type = 1 AND is_primary_key = 1
*/
set #sql=
'
use '+#DBName+'
SELECT DISTINCT PKObject = cco.object_id
FROM sys.key_constraints cco
JOIN sys.index_columns cc ON cco.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id
JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
join sys.schemas s on cco.schema_id=s.schema_id and s.name=#schema
WHERE OBJECT_NAME(parent_object_id) = #TableName AND i.type = 2 AND is_primary_key = 0 AND is_unique_constraint = 1
'
print #sql
INSERT INTO #Uniques(ObjectID)
exec sp_executesql #sql,
N'#TableName varchar(50),#schema varchar(50)',
#TableName=#TableName,#schema=#schema
/*
SELECT DISTINCT PKObject = cco.object_id
FROM sys.key_constraints cco
JOIN sys.index_columns cc ON cco.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id
JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
WHERE OBJECT_NAME(parent_object_id) = #TableName AND i.type = 2 AND is_primary_key = 0 AND is_unique_constraint = 1
*/
SET #ClusteredPK = CASE WHEN ##ROWCOUNT > 0 THEN 1 ELSE 0 END
declare #t TestTableType
insert #t select * from #PKObjectID
declare #u TestTableType
insert #u select * from #Uniques
set #sql=
'
use '+#DBName+'
SELECT distinct '',CONSTRAINT '' + replace(cco.name,#TableName,#NewTableName) + CASE type WHEN ''PK'' THEN '' PRIMARY KEY '' + CASE WHEN pk.ObjectID IS NULL THEN '' NONCLUSTERED '' ELSE '' CLUSTERED '' END WHEN ''UQ'' THEN '' UNIQUE '' END + CASE WHEN u.ObjectID IS NOT NULL THEN '' NONCLUSTERED '' ELSE '''' END
+ ''(''+REVERSE(SUBSTRING(REVERSE(( SELECT c.name + + CASE WHEN cc.is_descending_key = 1 THEN '' DESC'' ELSE '' ASC'' END + '',''
FROM sys.key_constraints ccok
LEFT JOIN sys.index_columns cc ON ccok.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id
LEFT JOIN sys.columns c ON cc.object_id = c.object_id AND cc.column_id = c.column_id
LEFT JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
WHERE i.object_id = ccok.parent_object_id AND ccok.object_id = cco.object_id
order by key_ordinal FOR XML PATH(''''))), 2, 8000)) + '')''
FROM sys.key_constraints cco
inner join sys.schemas s on cco.schema_id=s.schema_id and s.name=#schema
LEFT JOIN #U u ON cco.object_id = u.objectID
LEFT JOIN #t pk ON cco.object_id = pk.ObjectID
WHERE OBJECT_NAME(cco.parent_object_id) = #TableName
'
print #sql
INSERT INTO #Definition(FieldValue)
exec sp_executesql #sql,
N'#TableName varchar(50),#NewTableName varchar(50),#schema varchar(50),#t TestTableType readonly,#u TestTableType readonly',
#TableName=#TableName,#NewTableName=#NewTableName,#schema=#schema,#t=#t,#u=#u
/*
SELECT ',CONSTRAINT ' + name + CASE type WHEN 'PK' THEN ' PRIMARY KEY ' + CASE WHEN pk.ObjectID IS NULL THEN ' NONCLUSTERED ' ELSE ' CLUSTERED ' END WHEN 'UQ' THEN ' UNIQUE ' END + CASE WHEN u.ObjectID IS NOT NULL THEN ' NONCLUSTERED ' ELSE '' END
+ '(' +REVERSE(SUBSTRING(REVERSE(( SELECT c.name + + CASE WHEN cc.is_descending_key = 1 THEN ' DESC' ELSE ' ASC' END + ','
FROM sys.key_constraints ccok
LEFT JOIN sys.index_columns cc ON ccok.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id
LEFT JOIN sys.columns c ON cc.object_id = c.object_id AND cc.column_id = c.column_id
LEFT JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
WHERE i.object_id = ccok.parent_object_id AND ccok.object_id = cco.object_id FOR XML PATH(''))), 2, 8000)) + ')'
FROM sys.key_constraints cco
LEFT JOIN #PKObjectID pk ON cco.object_id = pk.ObjectID
LEFT JOIN #Uniques u ON cco.object_id = u.objectID
WHERE OBJECT_NAME(cco.parent_object_id) = #TableName
*/
END
INSERT INTO #Definition(FieldValue) VALUES(')')
set #sql=
'
use '+#DBName+'
select '' on '' + d.name + ''([''+c.name+''])''
from sys.tables t join sys.indexes i on(i.object_id = t.object_id and i.index_id < 2)
join sys.index_columns ic on(ic.partition_ordinal > 0 and ic.index_id = i.index_id and ic.object_id = t.object_id)
join sys.columns c on(c.object_id = ic.object_id and c.column_id = ic.column_id)
join sys.schemas s on t.schema_id=s.schema_id
join sys.data_spaces d on i.data_space_id=d.data_space_id
where t.name=#TableName and s.name=#schema
order by key_ordinal
'
print 'x'
print #sql
INSERT INTO #Definition(FieldValue)
exec sp_executesql #sql,
N'#TableName varchar(50),#schema varchar(50)',
#TableName=#TableName,#schema=#schema
IF #IncludeIndexes = 1
BEGIN
set #sql=
'
use '+#DBName+'
SELECT distinct '' CREATE '' + i.type_desc + '' INDEX ['' + replace(i.name COLLATE SQL_Latin1_General_CP1_CI_AS,#TableName,#NewTableName) + ''] ON '+#DBName+'.'+#NewTableSchema+'.'+#NewTableName+' (''
+ REVERSE(SUBSTRING(REVERSE(( SELECT name + CASE WHEN sc.is_descending_key = 1 THEN '' DESC'' ELSE '' ASC'' END + '',''
FROM sys.index_columns sc
JOIN sys.columns c ON sc.object_id = c.object_id AND sc.column_id = c.column_id
WHERE t.name=#TableName AND sc.object_id = i.object_id AND sc.index_id = i.index_id
and is_included_column=0
ORDER BY key_ordinal ASC FOR XML PATH('''') )), 2, 8000)) + '')''+
ISNULL( '' include (''+REVERSE(SUBSTRING(REVERSE(( SELECT name + '',''
FROM sys.index_columns sc
JOIN sys.columns c ON sc.object_id = c.object_id AND sc.column_id = c.column_id
WHERE t.name=#TableName AND sc.object_id = i.object_id AND sc.index_id = i.index_id
and is_included_column=1
ORDER BY key_ordinal ASC FOR XML PATH('''') )), 2, 8000))+'')'' ,'''')+''''
FROM sys.indexes i join sys.tables t on i.object_id=t.object_id
join sys.schemas s on t.schema_id=s.schema_id
AND CASE WHEN #ClusteredPK = 1 AND is_primary_key = 1 AND i.type = 1 THEN 0 ELSE 1 END = 1 AND is_unique_constraint = 0 AND is_primary_key = 0
where t.name=#TableName and s.name=#schema
'
print #sql
INSERT INTO #Definition(FieldValue)
exec sp_executesql #sql,
N'#TableName varchar(50),#NewTableName varchar(50),#schema varchar(50), #ClusteredPK bit',
#TableName=#TableName,#NewTableName=#NewTableName,#schema=#schema,#ClusteredPK=#ClusteredPK
END
/*
SELECT 'CREATE ' + type_desc + ' INDEX [' + [name] COLLATE SQL_Latin1_General_CP1_CI_AS + '] ON [' + OBJECT_NAME(object_id) + '] (' + REVERSE(SUBSTRING(REVERSE(( SELECT name + CASE WHEN sc.is_descending_key = 1 THEN ' DESC' ELSE ' ASC' END + ','
FROM sys.index_columns sc
JOIN sys.columns c ON sc.object_id = c.object_id AND sc.column_id = c.column_id
WHERE OBJECT_NAME(sc.object_id) = #TableName AND sc.object_id = i.object_id AND sc.index_id = i.index_id
ORDER BY index_column_id ASC FOR XML PATH('') )), 2, 8000)) + ')'
FROM sys.indexes i
WHERE OBJECT_NAME(object_id) = #TableName
AND CASE WHEN #ClusteredPK = 1 AND is_primary_key = 1 AND type = 1 THEN 0 ELSE 1 END = 1 AND is_unique_constraint = 0 AND is_primary_key = 0
*/
INSERT INTO #MainDefinition(FieldValue)
SELECT FieldValue FROM #Definition
ORDER BY DefinitionID ASC
----------------------------------
declare #q varchar(max)
set #q=(select replace((SELECT FieldValue FROM #MainDefinition FOR XML PATH('')),'</FieldValue>',''))
set #script=(select REPLACE(#q,'<FieldValue>',''))
--drop type TestTableType
END try
-- ##############################################################################################################################################################################
BEGIN CATCH
BEGIN
-- INIZIO Procedura in errore =========================================================================================================================================================
PRINT '***********************************************************************************************************************************************************'
PRINT 'ErrorNumber : ' + CAST(ERROR_NUMBER() AS NVARCHAR(MAX))
PRINT 'ErrorSeverity : ' + CAST(ERROR_SEVERITY() AS NVARCHAR(MAX))
PRINT 'ErrorState : ' + CAST(ERROR_STATE() AS NVARCHAR(MAX))
PRINT 'ErrorLine : ' + CAST(ERROR_LINE() AS NVARCHAR(MAX))
PRINT 'ErrorMessage : ' + CAST(ERROR_MESSAGE() AS NVARCHAR(MAX))
PRINT '***********************************************************************************************************************************************************'
-- FINE Procedura in errore =========================================================================================================================================================
END
set #script=''
return -1
END CATCH
-- ##############################################################################################################################################################################
to exec it:
declare #s varchar(max)
exec [util_ScriptTable] 'db','schema_source','table_source',1,1,'schema_dest','tab_dest',0,#s output
select #s
and here sp to find different from source do destination:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--*************************************************************************************************'
-- confronta 2 tabelle e fornisce lo scrit di aggiornamento
-- Tabella : xxxxx
-- Creata da : E.Mantovanelli
-- Data creazione : 26-11-2013
-- Data modifica: 26-11-2013
--*************************************************************************************************'
/*
-- nn supporta il caso inm cui si rinomini una colonna(colonne nn coincidenti, esegue drop+add)
-- ID----|-----Data-----|-- User --------- | ---- Note
*/
ALTER PROCEDURE [dbo].[util_ScriptTable_Update]
#DBName SYSNAME
,#schema_1 sysname
,#TableName_1 SYSNAME
,#IncludeConstraints BIT = 1
,#IncludeIndexes BIT = 1
,#Schema_2 sysname
,#TableName_2 SYSNAME = NULL
,#UseSystemDataTypes BIT = 0
,#script varchar(max) output
AS
BEGIN try
if not exists (select * from sys.types where name = 'TestTableType')
create type TestTableType as table (ObjectID int)--drop type TestTableType
declare #sql nvarchar(max),
#t0 varchar(max),
#t1 varchar(max),
#t2 varchar(max),
#script_add varchar(max),
#script_drop varchar(max)
DECLARE #MainDefinition TABLE (FieldValue VARCHAR(max))
DECLARE #ClusteredPK_1 BIT,
#ClusteredPK_2 BIT
DECLARE #TableSchema NVARCHAR(255)
declare #partition varchar(max)
--SET #DBName = DB_NAME(DB_ID())
SELECT #TableName_1 = name FROM sysobjects WHERE id = OBJECT_ID(#TableName_1)
DECLARE #ShowFields_1 TABLE (FieldID INT IDENTITY(1,1)
,DatabaseName VARCHAR(100)
,TableOwner VARCHAR(100)
,TableName VARCHAR(100)
,FieldName VARCHAR(max)
,ColumnPosition INT
,ColumnDefaultValue VARCHAR(100)
,ColumnDefaultName VARCHAR(100)
,IsNullable BIT
,DataType VARCHAR(100)
,MaxLength varchar(10)
,NumericPrecision INT
,NumericScale INT
,DomainName VARCHAR(100)
,FieldListingName VARCHAR(110)
,FieldDefinition CHAR(1)
,IdentityColumn BIT
,IdentitySeed INT
,IdentityIncrement INT
,IsCharColumn BIT
,IsComputed varchar(255))
DECLARE #ShowFields_2 TABLE (FieldID INT IDENTITY(1,1)
,DatabaseName VARCHAR(100)
,TableOwner VARCHAR(100)
,TableName VARCHAR(100)
,FieldName VARCHAR(max)
,ColumnPosition INT
,ColumnDefaultValue VARCHAR(100)
,ColumnDefaultName VARCHAR(100)
,IsNullable BIT
,DataType VARCHAR(100)
,MaxLength varchar(10)
,NumericPrecision INT
,NumericScale INT
,DomainName VARCHAR(100)
,FieldListingName VARCHAR(110)
,FieldDefinition CHAR(1)
,IdentityColumn BIT
,IdentitySeed INT
,IdentityIncrement INT
,IsCharColumn BIT
,IsComputed varchar(255))
DECLARE #HoldingArea TABLE(FldID SMALLINT IDENTITY(1,1)
,Flds VARCHAR(4000)
,FldValue CHAR(1) DEFAULT(0))
DECLARE #PKObjectID TABLE(ObjectID INT)
DECLARE #Uniques TABLE(ObjectID INT)
DECLARE #HoldingAreaValues TABLE(FldID SMALLINT IDENTITY(1,1)
,Flds VARCHAR(4000)
,FldValue CHAR(1) DEFAULT(0))
DECLARE #Definition TABLE(--DefinitionID SMALLINT IDENTITY(1,1)
state int
,FieldValue_1 VARCHAR(max),FieldValue_2 VARCHAR(max))
------------------------------
--FK
------------------------------
delete #Definition
delete #ShowFields_1
delete #ShowFields_2
set #sql=
'
use '+#DBName+'
SELECT distinct db_name(),#schema,ParentObject,name, ''('' + ParentColumns + '') REFERENCES ['' + ReferencedObject + '']('' + ReferencedColumns + '')''
FROM ( SELECT ReferencedObject = OBJECT_NAME(fk.referenced_object_id), ParentObject = OBJECT_NAME(parent_object_id),fk.name
, REVERSE(SUBSTRING(REVERSE(( SELECT cp.name + '',''
FROM sys.foreign_key_columns fkc
JOIN sys.columns cp ON fkc.parent_object_id = cp.object_id AND fkc.parent_column_id = cp.column_id
WHERE fkc.constraint_object_id = fk.object_id FOR XML PATH('''') )), 2, 8000)) ParentColumns,
REVERSE(SUBSTRING(REVERSE(( SELECT cr.name + '',''
FROM sys.foreign_key_columns fkc
JOIN sys.columns cr ON fkc.referenced_object_id = cr.object_id AND fkc.referenced_column_id = cr.column_id
WHERE fkc.constraint_object_id = fk.object_id FOR XML PATH('''') )), 2, 8000)) ReferencedColumns
FROM sys.foreign_keys fk
inner join sys.schemas s on fk.schema_id=s.schema_id and s.name=#schema) a
WHERE ParentObject = #TableName
'
print #sql
INSERT INTO #ShowFields_1( DatabaseName
,TableOwner
,TableName
,ColumnDefaultName
,FieldName
)
exec sp_executesql #sql,
N'#TableName varchar(50),#schema varchar(50)',
#TableName=#tablename_1,#schema=#schema_1
INSERT INTO #ShowFields_2( DatabaseName
,TableOwner
,TableName
,ColumnDefaultName
,FieldName
)
exec sp_executesql #sql,
N'#TableName varchar(50),#schema varchar(50)',
#TableName=#tablename_2,#schema=#schema_2
INSERT INTO #Definition(FieldValue_1)
select '['+#TableName_2+'_'+RIGHT(substring(convert(varchar(10),RAND()),3,10),10)+'] FOREIGN KEY '+FieldName+','
from
(
select COUNT(*)c,MAX(TableOwner)s,MAX(TableName)t,FieldName from
(
select * from #ShowFields_1 union all
select * from #ShowFields_2
)t
group by FieldName
)t
where c=1 and s=#schema_1 and t=#TableName_1
INSERT INTO #Definition(FieldValue_2)
select '['+k+'],'
from
(
select COUNT(*)c,MAX(TableOwner)s,MAX(TableName)t,MAX(ColumnDefaultName)k,FieldName from
(
select * from #ShowFields_1 union all
select * from #ShowFields_2
)t
group by FieldName
)t
where c=1 and s=#schema_2 and t=#TableName_2
set #t1=case when (select COUNT(FieldValue_1) from #Definition)>0 then (select ' alter table '+#Schema_2+'.'+#TableName_2+' add CONSTRAINT'+(replace((select replace((SELECT SUBSTRING(FieldValue_1,0,LEN(FieldValue_1)+1) FROM #Definition FOR XML PATH('')),'</FieldValue_1>','')),'<FieldValue_1>',''))) else '' end
set #t2=case when (select COUNT(FieldValue_2) from #Definition)>0 then (select ' alter table '+#Schema_2+'.'+#TableName_2+' drop CONSTRAINT '+(replace((select replace((SELECT SUBSTRING(FieldValue_2,0,LEN(FieldValue_2)+1) FROM #Definition FOR XML PATH('')),'</FieldValue_2>','')),'<FieldValue_2>',''))) else '' end
--prima la drop, poi la add
set #script_drop =' '+ substring(#t2,0,len(#t2))
set #script_add =' '+ substring(#t1,0,len(#t1))
-----------------------------
--Keys
-----------------------------
delete #Definition
delete #ShowFields_1
delete #ShowFields_2
set #sql=
'
use '+#DBName+'
SELECT DISTINCT PKObject = cco.object_id
FROM sys.key_constraints cco
JOIN sys.index_columns cc ON cco.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id
JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
join sys.schemas s on cco.schema_id=s.schema_id and s.name=#schema
WHERE OBJECT_NAME(parent_object_id) = #TableName AND i.type = 1 AND is_primary_key = 1
'
print #sql
INSERT INTO #PKObjectID(ObjectID)
exec sp_executesql #sql,
N'#TableName varchar(50),#schema varchar(50)',
#TableName=#TableName_1,#schema=#schema_1
print #sql
INSERT INTO #PKObjectID(ObjectID)
exec sp_executesql #sql,
N'#TableName varchar(50),#schema varchar(50)',
#TableName=#TableName_2,#schema=#schema_2
/*
SELECT DISTINCT PKObject = cco.object_id
FROM sys.key_constraints cco
JOIN sys.index_columns cc ON cco.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id
JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
WHERE OBJECT_NAME(parent_object_id) = #TableName AND i.type = 1 AND is_primary_key = 1
*/
set #sql=
'
use '+#DBName+'
SELECT DISTINCT PKObject = cco.object_id
FROM sys.key_constraints cco
JOIN sys.index_columns cc ON cco.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id
JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
join sys.schemas s on cco.schema_id=s.schema_id and s.name=#schema
WHERE OBJECT_NAME(parent_object_id) = #TableName AND i.type = 2 AND is_primary_key = 0 AND is_unique_constraint = 1
'
print #sql
INSERT INTO #Uniques(ObjectID)
exec sp_executesql #sql,
N'#TableName varchar(50),#schema varchar(50)',
#TableName=#TableName_1,#schema=#schema_1
SET #ClusteredPK_1 = CASE WHEN ##ROWCOUNT > 0 THEN 1 ELSE 0 END
print #sql
INSERT INTO #Uniques(ObjectID)
exec sp_executesql #sql,
N'#TableName varchar(50),#schema varchar(50)',
#TableName=#TableName_2,#schema=#schema_2
SET #ClusteredPK_2 = CASE WHEN ##ROWCOUNT > 0 THEN 1 ELSE 0 END
--------------------------------------
--PK
--------------------------------------
delete #Definition
delete #ShowFields_1
delete #ShowFields_2
set #sql=
'
use '+#DBName+'
SELECT distinct db_name(),#schema,#TableName,cco.name,CASE type WHEN ''PK'' THEN '' PRIMARY KEY '' + CASE WHEN pk.ObjectID IS NULL THEN '' NONCLUSTERED '' ELSE '' CLUSTERED '' END WHEN ''UQ'' THEN '' UNIQUE '' END + CASE WHEN u.ObjectID IS NOT NULL THEN '' NONCLUSTERED '' ELSE '''' END
+ ''(''+REVERSE(SUBSTRING(REVERSE(( SELECT c.name + + CASE WHEN cc.is_descending_key = 1 THEN '' DESC'' ELSE '' ASC'' END + '',''
FROM sys.key_constraints ccok
LEFT JOIN sys.index_columns cc ON ccok.parent_object_id = cc.object_id AND cco.unique_index_id = cc.index_id
LEFT JOIN sys.columns c ON cc.object_id = c.object_id AND cc.column_id = c.column_id
LEFT JOIN sys.indexes i ON cc.object_id = i.object_id AND cc.index_id = i.index_id
WHERE i.object_id = ccok.parent_object_id AND ccok.object_id = cco.object_id
order by key_ordinal FOR XML PATH(''''))), 2, 8000)) + '')''
FROM sys.key_constraints cco
inner join sys.schemas s on cco.schema_id=s.schema_id and s.name=#schema
LEFT JOIN #U u ON cco.object_id = u.objectID
LEFT JOIN #t pk ON cco.object_id = pk.ObjectID
WHERE OBJECT_NAME(cco.parent_object_id) = #TableName
'
declare #t TestTableType
insert #t select * from #PKObjectID
declare #u TestTableType
insert #u select * from #Uniques
print #sql
INSERT INTO #ShowFields_1( DatabaseName
,TableOwner
,TableName
,ColumnDefaultName
,FieldName
)
exec sp_executesql #sql,
N'#TableName varchar(50),#schema varchar(50),#t TestTableType readonly,#u TestTableType readonly',
#TableName=#TableName_1,#schema=#schema_1,#t=#t,#u=#u
INSERT INTO #ShowFields_2( DatabaseName
,TableOwner
,TableName
,ColumnDefaultName
,FieldName
)
exec sp_executesql #sql,
N'#TableName varchar(50),#schema varchar(50),#t TestTableType readonly,#u TestTableType readonly',
#TableName=#TableName_2,#schema=#schema_2,#t=#t,#u=#u
INSERT INTO #Definition(FieldValue_1)
select ' alter table '+#Schema_2+'.'+#TableName_2+' add constraint ['+k+'] '+FieldName+';'
from
(
select COUNT(*)c,MAX(TableOwner)s,MAX(TableName)t,MAX(ColumnDefaultName)k,FieldName from
(
select * from #ShowFields_1 union all
select * from #ShowFields_2
)t
group by FieldName
)t
where c=1 and s=#schema_1 and t=#TableName_1
INSERT INTO #Definition(FieldValue_2)
select ' alter table '+#Schema_2+'.'+#TableName_2+' drop constraint ['+k+'] ;'
from
(
select COUNT(*)c,MAX(TableOwner)s,MAX(TableName)t,MAX(ColumnDefaultName)k,FieldName from
(
select * from #ShowFields_1 union all
select * from #ShowFields_2
)t
group by FieldName
)t
where c=1 and s=#schema_2 and t=#TableName_2
set #t1=case when (select COUNT(FieldValue_1) from #Definition)>0 then ((replace((select replace((SELECT SUBSTRING(FieldValue_1,0,LEN(FieldValue_1)+1) FROM #Definition FOR XML PATH('')),'</FieldValue_1>','')),'<FieldValue_1>',''))) else '' end
set #t2=case when (select COUNT(FieldValue_2) from #Definition)>0 then ((replace((select replace((SELECT SUBSTRING(FieldValue_2,0,LEN(FieldValue_2)+1) FROM #Definition FOR XML PATH('')),'</FieldValue_2>','')),'<FieldValue_2>',''))) else '' end
--prima la drop, poi la add
set #script_drop +=' '+ substring(#t2,0,len(#t2))
set #script_add =substring(#t1,0,len(#t1))+ ' ' +#script_add
--------------------------------------
--Partition
--------------------------------------
delete #Definition
delete #ShowFields_1
delete #ShowFields_2
set #sql=
'
use '+#DBName+'
select #partition='' on '' + d.name + ''([''+c.name+''])''
from sys.tables t join sys.indexes i on(i.object_id = t.object_id and i.index_id < 2)
join sys.index_columns ic on(ic.partition_ordinal > 0 and ic.index_id = i.index_id and ic.object_id = t.object_id)
join sys.columns c on(c.object_id = ic.object_id and c.column_id = ic.column_id)
join sys.schemas s on t.schema_id=s.schema_id
join sys.data_spaces d on i.data_space_id=d.data_space_id
where t.name=#TableName and s.name=#schema
order by key_ordinal
'
print 'x'
print #sql
exec sp_executesql #sql,
N'#TableName varchar(50),#schema varchar(50),#partition varchar(max) output',
#TableName=#TableName_1,#schema=#schema_1,#partition=#partition output
if(#partition is null)
set #partition=''
--select #partition
--------------------------------------
--Indexes
--------------------------------------
delete #Definition
delete #ShowFields_1
delete #ShowFields_2
IF #IncludeIndexes = 1
BEGIN
set #sql=
'
use '+#DBName+'
SELECT DB_NAME(),s.name,t.name,i.name COLLATE SQL_Latin1_General_CP1_CI_AS, i.type_desc ,''(''+REVERSE(SUBSTRING(REVERSE(( SELECT name + CASE WHEN sc.is_descending_key = 1 THEN '' DESC'' ELSE '' ASC'' END + '',''
FROM sys.index_columns sc
JOIN sys.columns c ON sc.object_id = c.object_id AND sc.column_id = c.column_id
WHERE t.name=#TableName AND sc.object_id = i.object_id
AND sc.index_id = i.index_id
and t.schema_id=s.schema_id
and is_included_column=0
--caso di tabelle partizionate
--inserisce in automatico la pk
and (key_ordinal!=0 or partition_ordinal!=1)
ORDER BY key_ordinal ASC FOR XML PATH('''') )), 2, 8000)) + '')''+
ISNULL( '' include (''+REVERSE(SUBSTRING(REVERSE(( SELECT name + '',''
FROM sys.index_columns sc
JOIN sys.columns c ON sc.object_id = c.object_id AND sc.column_id = c.column_id
WHERE t.name=#TableName AND sc.object_id = i.object_id
AND sc.index_id = i.index_id
and t.schema_id=s.schema_id
and is_included_column=1
ORDER BY key_ordinal ASC FOR XML PATH('''') )), 2, 8000))+'')'' ,'''')+''''
FROM sys.indexes i join sys.tables t on i.object_id=t.object_id
join sys.schemas s on t.schema_id=s.schema_id
AND CASE WHEN #ClusteredPK = 1 AND is_primary_key = 1 AND i.type = 1 THEN 0 ELSE 1 END = 1 AND is_unique_constraint = 0 AND is_primary_key = 0
where t.name=#TableName and s.name=#schema
'
print #ClusteredPK_1
print #sql
INSERT INTO #ShowFields_1( DatabaseName
,TableOwner
,TableName
,ColumnDefaultName
,ColumnDefaultValue
,FieldName
)
exec sp_executesql #sql,
N'#TableName varchar(50),#schema varchar(50), #ClusteredPK bit',
#TableName=#TableName_1,#schema=#schema_1,#ClusteredPK=#ClusteredPK_1
INSERT INTO #ShowFields_2( DatabaseName
,TableOwner
,TableName
,ColumnDefaultName
,ColumnDefaultValue
,FieldName
)
exec sp_executesql #sql,
N'#TableName varchar(50),#schema varchar(50), #ClusteredPK bit',
#TableName=#TableName_2,#schema=#schema_2,#ClusteredPK=#ClusteredPK_2
INSERT INTO #Definition(FieldValue_1)
select 'create '+ColumnDefaultValue+' index ['+n+'] on '+#schema_2+'.'+#TableName_2+FieldName+#partition+';'
from
(
select COUNT(*)c,MAX(TableOwner)s,MAX(TableName)t,MAX(ColumnDefaultName)n,ColumnDefaultValue,FieldName from
(
select * from #ShowFields_1 union all
select * from #ShowFields_2
)t
group by ColumnDefaultValue,FieldName
)t
where c=1 and s=#schema_1 and t=#TableName_1
INSERT INTO #Definition(FieldValue_2)
select 'drop index ['+n+'] on '+#schema_2+'.'+#TableName_2+' ;'
from
(
select COUNT(*)c,MAX(TableOwner)s,MAX(TableName)t,MAX(ColumnDefaultName)n,ColumnDefaultValue,FieldName from
(
select * from #ShowFields_1 union all
select * from #ShowFields_2
)t
group by ColumnDefaultValue,FieldName
)t
where c=1 and s=#schema_2 and t=#TableName_2
set #t1=case when (select COUNT(FieldValue_1) from #Definition)>0 then ((replace((select replace((SELECT SUBSTRING(FieldValue_1,0,LEN(FieldValue_1)+1) FROM #Definition FOR XML PATH('')),'</FieldValue_1>','')),'<FieldValue_1>',''))) else '' end
set #t2=case when (select COUNT(FieldValue_2) from #Definition)>0 then ((replace((select replace((SELECT SUBSTRING(FieldValue_2,0,LEN(FieldValue_2)+1) FROM #Definition FOR XML PATH('')),'</FieldValue_2>','')),'<FieldValue_2>',''))) else '' end
--prima la drop, poi la add
set #script_drop +=' '+ substring(#t2,0,len(#t2))
set #script_add =substring(#t1,0,len(#t1))+ ' ' +#script_add
END
-----------------------------
--Columns
-----------------------------
delete #Definition
delete #ShowFields_1
delete #ShowFields_2
set #sql=
'
use '+#DBName+'
SELECT distinct DB_NAME()
,TABLE_SCHEMA
,TABLE_NAME
,''[''+COLUMN_NAME+'']'' as COLUMN_NAME
,CAST(ORDINAL_POSITION AS INT)
,COLUMN_DEFAULT
,dobj.name AS ColumnDefaultName
,CASE WHEN c.IS_NULLABLE = ''YES'' THEN 1 ELSE 0 END
,DATA_TYPE
,case CHARACTER_MAXIMUM_LENGTH when -1 then ''max'' else CAST(CHARACTER_MAXIMUM_LENGTH AS varchar) end--CAST(CHARACTER_MAXIMUM_LENGTH AS INT)
,CAST(NUMERIC_PRECISION AS INT)
,CAST(NUMERIC_SCALE AS INT)
,DOMAIN_NAME
,COLUMN_NAME + '',''
,'''' AS FieldDefinition
,CASE WHEN ic.object_id IS NULL THEN 0 ELSE 1 END AS IdentityColumn
,CAST(ISNULL(ic.seed_value,0) AS INT) AS IdentitySeed
,CAST(ISNULL(ic.increment_value,0) AS INT) AS IdentityIncrement
,CASE WHEN st.collation_name IS NOT NULL THEN 1 ELSE 0 END AS IsCharColumn
,cc.definition
FROM INFORMATION_SCHEMA.COLUMNS c
JOIN sys.columns sc ON c.TABLE_NAME = OBJECT_NAME(sc.object_id) AND c.COLUMN_NAME = sc.Name
LEFT JOIN sys.identity_columns ic ON c.TABLE_NAME = OBJECT_NAME(ic.object_id) AND c.COLUMN_NAME = ic.Name
JOIN sys.types st ON COALESCE(c.DOMAIN_NAME,c.DATA_TYPE) = st.name
LEFT OUTER JOIN sys.objects dobj ON dobj.object_id = sc.default_object_id AND dobj.type = ''D''
left join sys.computed_columns cc on c.TABLE_NAME=OBJECT_NAME(cc.object_id) and sc.column_id=cc.column_id
WHERE c.TABLE_NAME = #TableName and c.TABLE_SCHEMA=#schema
ORDER BY c.TABLE_NAME, c.ORDINAL_POSITION
'
print #sql
INSERT INTO #ShowFields_1( DatabaseName
,TableOwner
,TableName
,FieldName
,ColumnPosition
,ColumnDefaultValue
,ColumnDefaultName
,IsNullable
,DataType
,MaxLength
,NumericPrecision
,NumericScale
,DomainName
,FieldListingName
,FieldDefinition
,IdentityColumn
,IdentitySeed
,IdentityIncrement
,IsCharColumn
,IsComputed)
exec sp_executesql #sql,
N'#TableName varchar(50),#schema varchar(50)',
#TableName=#TableName_1,#schema=#schema_1
INSERT INTO #ShowFields_2( DatabaseName
,TableOwner
,TableName
,FieldName
,ColumnPosition
,ColumnDefaultValue
,ColumnDefaultName
,IsNullable
,DataType
,MaxLength
,NumericPrecision
,NumericScale
,DomainName
,FieldListingName
,FieldDefinition
,IdentityColumn
,IdentitySeed
,IdentityIncrement
,IsCharColumn
,IsComputed)
exec sp_executesql #sql,
N'#TableName varchar(50),#schema varchar(50)',
#TableName=#TableName_2,#schema=#schema_2
----------------------------------
INSERT INTO #Definition(state,FieldValue_1)
SELECT t2.c,t.FieldName + ' ' +
--CASE WHEN DomainName IS NOT NULL AND #UseSystemDataTypes = 0 THEN DomainName + CASE WHEN IsNullable = 1 THEN ' NULL ' ELSE ' NOT NULL ' END ELSE UPPER(DataType) +CASE WHEN IsCharColumn = 1 THEN '(' + CAST(MaxLength AS VARCHAR(10)) + ')' ELSE '' END +CASE WHEN IdentityColumn = 1 THEN ' IDENTITY(' + CAST(IdentitySeed AS VARCHAR(5))+ ',' + CAST(IdentityIncrement AS VARCHAR(5)) + ')' ELSE '' END +CASE WHEN IsNullable = 1 THEN ' NULL ' ELSE ' NOT NULL ' END +CASE WHEN ColumnDefaultName IS NOT NULL AND #IncludeConstraints = 1 THEN 'CONSTRAINT [' + ColumnDefaultName + '] DEFAULT' + UPPER(ColumnDefaultValue) ELSE '' END END + CASE WHEN FieldID = (SELECT MAX(FieldID) FROM #ShowFields) THEN '' ELSE ',' END
CASE WHEN DomainName IS NOT NULL AND #UseSystemDataTypes = 0 THEN DomainName +
CASe WHEN IsNullable = 1 THEN ' NULL '
ELSE ' NOT NULL '
END
ELSE
case when IsComputed is null then
UPPER(DataType) +
CASE WHEN IsCharColumn = 1 THEN '(' + CAST(MaxLength AS VARCHAR(10)) + ')'
ELSE
CASE WHEN DataType = 'numeric' THEN '(' + CAST(NumericPrecision AS VARCHAR(10))+','+ CAST(NumericScale AS VARCHAR(10)) + ')'
ELSE
CASE WHEN DataType = 'decimal' THEN '(' + CAST(NumericPrecision AS VARCHAR(10))+','+ CAST(NumericScale AS VARCHAR(10)) + ')'
ELSE ''
end
end
END +
CASE WHEN IdentityColumn = 1 THEN ' IDENTITY(' + CAST(IdentitySeed AS VARCHAR(5))+ ',' + CAST(IdentityIncrement AS VARCHAR(5)) + ')'
ELSE ''
END +
CASE WHEN IsNullable = 1 THEN ' NULL '
ELSE ' NOT NULL '
END +
CASE WHEN ColumnDefaultName IS NOT NULL AND #IncludeConstraints = 1 THEN 'CONSTRAINT [' + replace(ColumnDefaultName,#TableName_1,#TableName_2) + '] DEFAULT' + UPPER(ColumnDefaultValue)
ELSE ''
END
else
' as '+IsComputed+' '
end
END +
--, per add, ; per alter
CASE WHEN t2.c = 1 THEN ','
ELSE ';'
END
from
(
select *
FROM
( --escludo la ColumnPosition xkè:
-- c1, c2, c3
-- cancello c2 e aggiungo c4 quindi
-- c1, c3, c4
-- c2 è in posizione 2
-- se considero anche la ColumnPosition c3 sarebbe da cancellare e ricreare, e perderei i dati
-- in qsto modo mantengo la stessa colonna che con la drop delle altre si rimette al suo posto
-- ATTENZIONE.!!.
-- se cancello c2 e poi lo ricreo (passa da posizione 2 a posizione 3) nn percepisco il cambiamento
select COUNT(*)c,MAX(TableOwner) s,MAX(TableName) t,MAX(ColumnPosition)p
,FieldName,ColumnDefaultValue,ColumnDefaultName,IsNullable,DataType
,MaxLength,NumericPrecision,NumericScale,DomainName,FieldListingName,FieldDefinition
,IdentityColumn,IdentitySeed,IdentityIncrement,IsCharColumn,IsComputed
from
(
select * from #ShowFields_1 union all
select * from #ShowFields_2
--order by TableOwner,TableName,ColumnPosition
)t
group by FieldName,ColumnDefaultValue,ColumnDefaultName,IsNullable,DataType
,MaxLength,NumericPrecision,NumericScale,DomainName,FieldListingName,FieldDefinition
,IdentityColumn,IdentitySeed,IdentityIncrement,IsCharColumn,IsComputed
)t
where s=#schema_1 and t=#TableName_1 and c=1
)t
--distinguo le colonne columi(t2.c=2 -> alter column; t2.c=1 -> add column)
join
(
select FieldName,COUNT(*)c from
(
select FieldName from #ShowFields_1 union all
select FieldName from #ShowFields_2
)a
group by FieldName
)t2 on t.FieldName=t2.FieldName
order by s,t,p--,ColumnPosition
INSERT INTO #Definition(FieldValue_2)
SELECT ' '+t.FieldName + ', '
from
(
select *
FROM
( --escludo la ColumnPosition xkè:
-- c1, c2, c3
-- cancello c2 e aggiungo c4 quindi
-- c1, c3, c4
-- c2 è in posizione 2
-- se considero anche la ColumnPosition c3 sarebbe da cancellare e ricreare, e perderei i dati
-- in qsto modo mantengo la stessa colonna che con la drop delle altre si rimette al suo posto
-- ATTENZIONE.!!.
-- se cancello c2 e poi lo ricreo (passa da posizione 2 a posizione 3) nn percepisco il cambiamento
select COUNT(*)c,MAX(TableOwner) s,MAX(TableName) t--,MAX(ColumnPosition)p
,FieldName,ColumnDefaultValue,ColumnDefaultName,IsNullable,DataType
,MaxLength,NumericPrecision,NumericScale,DomainName,FieldListingName,FieldDefinition
,IdentityColumn,IdentitySeed,IdentityIncrement,IsCharColumn,IsComputed
from
(
select * from #ShowFields_1 union all
select * from #ShowFields_2
--order by TableOwner,TableName,ColumnPosition
)t
group by FieldName,ColumnDefaultValue,ColumnDefaultName,IsNullable,DataType
,MaxLength,NumericPrecision,NumericScale,DomainName,FieldListingName,FieldDefinition
,IdentityColumn,IdentitySeed,IdentityIncrement,IsCharColumn,IsComputed
)t
where s=#schema_2 and t=#TableName_2 and c=1
)t
--distinguo le colonne columi tra le tabelle(t2.c=2 -> alter column; t2.c=1 -> add column)
join
(
select FieldName,COUNT(*)c from
(
select FieldName from #ShowFields_1 union all
select FieldName from #ShowFields_2
)a
group by FieldName
having COUNT(*)=1
)t2 on t.FieldName=t2.FieldName
order by s,t--,ColumnPosition
--state=1 -> add
--state=2 -> alter
set #t0=case when (select COUNT(FieldValue_1) from #Definition where state=1)>0 then (select ' alter table '+#Schema_2+'.'+#TableName_2+' add '+(replace((select replace((SELECT SUBSTRING(FieldValue_1,0,LEN(FieldValue_1)+1) FROM #Definition where state=1 FOR XML PATH('')),'</FieldValue_1>','')),'<FieldValue_1>',''))) else '' end
set #t1=case when (select COUNT(FieldValue_1) from #Definition where state=2)>0 then (select (replace((select replace((SELECT ' alter table '+#Schema_2+'.'+#TableName_2+' alter column '+SUBSTRING(FieldValue_1,0,LEN(FieldValue_1)+1) FROM #Definition where state=2 FOR XML PATH('')),'</FieldValue_1>','')),'<FieldValue_1>',''))) else '' end
set #t2=case when (select COUNT(FieldValue_2) from #Definition)>0 then (select ' alter table '+#Schema_2+'.'+#TableName_2+' drop column '+(replace((select replace((SELECT SUBSTRING(FieldValue_2,0,LEN(FieldValue_2)+1) FROM #Definition FOR XML PATH('')),'</FieldValue_2>','')),'<FieldValue_2>',''))) else '' end
--prima la drop, poi la add
set #script_drop +=' '+ substring(#t2,0,len(#t2))
set #script_add =substring(#t0,0,len(#t0)) + ' ' + substring(#t1,0,len(#t1))+ ' ' +#script_add
set #script=#script_drop+#script_add
END try
-- ##############################################################################################################################################################################
BEGIN CATCH
BEGIN
PRINT 'ErrorNumber : ' + CAST(ERROR_NUMBER() AS NVARCHAR(MAX))
PRINT 'ErrorSeverity : ' + CAST(ERROR_SEVERITY() AS NVARCHAR(MAX))
PRINT 'ErrorState : ' + CAST(ERROR_STATE() AS NVARCHAR(MAX))
PRINT 'ErrorLine : ' + CAST(ERROR_LINE() AS NVARCHAR(MAX))
PRINT 'ErrorMessage : ' + CAST(ERROR_MESSAGE() AS NVARCHAR(MAX))
PRINT
END
set #script=''
return -1
END CATCH
to exec it:
declare #s varchar(max)
exec [util_ScriptTable_Update] 'db','schema_source','table_source',1,1,'schema_dest','tab_dest',0,#s output
select #s

Generate SQL Create Scripts for existing tables with Query

I'm trying to get the CREATE scripts for existing tables within SQL Server 2008. I assume I can do this by querying the sys.tables somehow, however this isn't returning me the CREATE script data.
Possible this be helpful for you. This script generate indexes, FK's, PK and common structure for any table.
For example -
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]
Query:
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
Output:
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])
Also check this article -
How to Generate a CREATE TABLE Script For an Existing Table: Part 1
do you mean you wish to create a TSQL script which generates a CREATE script, or use the Management tools in SQL SERVER Management Studio to generate a Create script?
If it's the latter, it's a simply matter of right-clicking a table, and selecting Script Table As -> Create To -> New Query Window.
If you want the whole database scripted, then right click the database and select Tasks--> Generate Scripts... and then follow the wizard
otherwise it's a matter of selecting all sorts of fun things out of the various system tables.
I realize this question is old, but it recently popped up in a search I just ran, so I thought I'd post an alternative to the above answer.
If you are looking to generate create scripts programmatically in .Net, I would highly recommend looking into Server Management Objects (SMO) or Distributed Management Objects (DMO) -- depending on which version of SQL Server you are using (the former is 2005+, the latter 2000). Using these libraries, scripting a table is as easy as:
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);
Here is a blog post with more information.
First of all I love the script written by devart and I wanted to use it, but I found some limitation, so I decided to improve it:
I fixed the bug that limits the script at 4000 chars (it's still possible that some crazy table still exceeds the limits)
I fixed the bug/limitation in case the table uses a nonclustered primary key
I replaced '[' with quotename
I added the name of the default constraints
I changed the logic to identify the source table
I added the possibility to drop and recreate the table and its FKs
I added the possibility to generate specific attributes
I added the support for table compression
I added the possibility the generate the scripts for any number of tables
I fixed the limitation of 4000 varchar() when printing the result
I replaced '' with N''
I added the option to generate messages during the execution, because my final script (with the insert into) can take so long that I want to know what it's doing
I added the generation of an "Insert into"
I didn't have time to test it properly and I tested it only on SQL Server 2012/4
The next version will change the generation of FKs because they need to be added at the end. Otherwise they may fail.
Any comment will be appreciated.
set transaction isolation level read uncommitted;
SET NOCOUNT ON;
SET STATISTICS TIME OFF;
SET STATISTICS IO OFF;
-- http://stackoverflow.com/questions/12639948/sql-nvarchar-and-varchar-limits
--NB: Crazy table can still have truncation at 4000 because of unexpected number of indexes or other very long list of columns/defaults etc
-- triggers are not supported
-- xml indexes are not supported
DECLARE #Tables table(id int identity(1,1), [name] sysname);
insert into #Tables([name])
values
('<yourSchema>.<youTableName>')
,('<yourSchema2>.<youTableName2>')
;
DECLARE #object_id int;
DECLARE #SourceDatabase nvarchar(max) = N'SourceTest'; --this is used only by the insert
DECLARE #TargetDatabase nvarchar(max) = N'DescTest'; --this is used only by the insert and USE <DBName>
--- options ---
DECLARE #UseTransaction bit = 0;
DECLARE #GenerateUseDatabase bit = 0;
DECLARE #GenerateFKs bit = 1;
DECLARE #GenerateIdentity bit = 1;
DECLARE #GenerateCollation bit = 0;
DECLARE #GenerateCreateTable bit = 1;
DECLARE #GenerateIndexes bit = 1;
DECLARE #GenerateConstraints bit = 1;
DECLARE #GenerateKeyConstraints bit = 1;
DECLARE #GenerateConstraintNameOfDefaults bit = 1;
DECLARE #GenerateDropIfItExists bit = 1;
DECLARE #GenerateDropFKIfItExists bit = 0;
DECLARE #GenerateDelete bit = 0;
DECLARE #GenerateInsertInto bit = 0;
DECLARE #GenerateIdentityInsert int = 0; --0 ignore set,but add column; 1 generate; 2 ignore set and column
DECLARE #GenerateSetNoCount int = 2; --0 ignore set,1=set on, 2=set off
DECLARE #GenerateMessages bit = 1; --print with no wait
DECLARE #GenerateDataCompressionOptions bit = 1; --TODO: generates the compression option only of the table, not the indexes
--NB: the compression options reflects the design value.
--The actual compression of a the page is saved here
--SELECT * from sys.dm_db_database_page_allocations(DB_ID(), #object_ID, 0, 1, 'DETAILED')
-----------------------------------------------------------------------------
------------------------------------------------------------------------------
--- Let's play
DECLARE #DataTypeSpacer int = 45; --this is just to improve the formatting of the script ...
DECLARE #name sysname;
DECLARE #SQL NVARCHAR(MAX) = N''
DECLARE db_cursor CURSOR FOR SELECT [name] from #Tables
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO #name
WHILE ##FETCH_STATUS = 0
BEGIN
SET #object_id = object_ID(#name)
goto CreateScript;
backFromCreateScript:
FETCH NEXT FROM db_cursor INTO #name
END
CLOSE db_cursor
DEALLOCATE db_cursor
return;
CreateScript:
DECLARE #CR NVARCHAR(max) = NCHAR(13);
DECLARE #TB NVARCHAR(max) = NCHAR(9);
DECLARE #CurrentIndent 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 and #GenerateFKs = 1
)
SELECT #SQL =
-------------------- USE DATABASE --------------------------------------------------------------------------------------------------
CAST(
CASE WHEN #GenerateUseDatabase = 1
THEN N'USE ' + #TargetDatabase + N';' + #CR
ELSE N'' END
as nvarchar(max))
+
-------------------- SET NOCOUNT --------------------------------------------------------------------------------------------------
CAST(
CASE #GenerateSetNoCount
WHEN 1 THEN N'SET NOCOUNT ON;' + #CR
WHEN 2 THEN N'SET NOCOUNT OFF;' + #CR
ELSE N'' END
as nvarchar(max))
+
-------------------- USE TRANSACTION --------------------------------------------------------------------------------------------------
CAST(
CASE WHEN #UseTransaction = 1
THEN
N'SET XACT_ABORT ON' + #CR
+ N'BEGIN TRY' + #CR
+ N'BEGIN TRAN' + #CR
ELSE N'' END
as nvarchar(max))
+
-------------------- DROP SYNONYM --------------------------------------------------------------------------------------------------
CASE WHEN #GenerateDropIfItExists = 1
THEN
CAST(
N'IF OBJECT_ID(''' + quotename(OBJECT_schema_name(#object_id)) + N'.' + quotename(OBJECT_NAME(#object_id)) + N''',''SN'') IS NOT NULL DROP SYNONYM ' + quotename(OBJECT_schema_name(#object_id)) + N'.' + quotename(OBJECT_NAME(#object_id)) + N';' + #CR
as nvarchar(max))
ELSE
CAST(
N''
as nvarchar(max))
END
+
-------------------- DROP IS Exists --------------------------------------------------------------------------------------------------
CASE WHEN #GenerateDropIfItExists = 1
THEN
--Drop table if exists
CAST(
N'IF OBJECT_ID(''' + quotename(OBJECT_schema_name(#object_id)) + N'.' + quotename(OBJECT_NAME(#object_id)) + N''',''U'') IS NOT NULL DROP TABLE ' + quotename(OBJECT_schema_name(#object_id)) + N'.' + quotename(OBJECT_NAME(#object_id)) + N';' + #CR
as nvarchar(max))
+ #CR
ELSE N'' END
+
-------------------- DROP IS Exists --------------------------------------------------------------------------------------------------
CAST((CASE WHEN #GenerateMessages = 1 and #GenerateDropFKIfItExists = 1 THEN
N'RAISERROR(''DROP CONSTRAINTS OF %s'',10,1, ''' + quotename(OBJECT_schema_name(#object_id)) + N'.' + quotename(OBJECT_NAME(#object_id)) + N''') WITH NOWAIT;' + #CR
ELSE N'' END) as nvarchar(max))
+
CASE WHEN #GenerateDropFKIfItExists = 1
THEN
--Drop foreign keys
ISNULL(((
SELECT
CAST(
N'ALTER TABLE ' + quotename(s.name) + N'.' + quotename(t.name) + N' DROP CONSTRAINT ' + RTRIM(f.name) + N';' + #CR
as nvarchar(max))
FROM sys.tables t
INNER JOIN sys.foreign_keys f ON f.parent_object_id = t.object_id
INNER JOIN sys.schemas s ON s.schema_id = f.schema_id
WHERE f.referenced_object_id = #object_id
FOR XML PATH(N''), TYPE).value(N'.', N'NVARCHAR(MAX)'))
,N'') + #CR
ELSE N'' END
+
--------------------- CREATE TABLE -----------------------------------------------------------------------------------------------------------------
CAST((CASE WHEN #GenerateMessages = 1 THEN
N'RAISERROR(''CREATE TABLE %s'',10,1, ''' + quotename(OBJECT_schema_name(#object_id)) + N'.' + quotename(OBJECT_NAME(#object_id)) + N''') WITH NOWAIT;' + #CR
ELSE N'' END) as nvarchar(max))
+
CASE WHEN #GenerateCreateTable = 1 THEN
CAST(
N'CREATE TABLE ' + quotename(OBJECT_schema_name(#object_id)) + N'.' + quotename(OBJECT_NAME(#object_id)) + #CR + N'(' + #CR + STUFF((
SELECT
CAST(
#TB + N',' + quotename(c.name) + N' ' + ISNULL(replicate(' ',#DataTypeSpacer - len(quotename(c.name))),'') --isnull(replicate) then len(quotename(c.name)) > #DataTypeSpacer
+
CASE WHEN c.is_computed = 1
THEN N' AS ' + cc.[definition]
ELSE UPPER(tp.name) +
CASE WHEN tp.name IN (N'varchar', N'char', N'varbinary', N'binary', N'text')
THEN N'(' + CASE WHEN c.max_length = -1 THEN N'MAX' ELSE CAST(c.max_length AS NVARCHAR(5)) END + N')'
WHEN tp.name IN (N'nvarchar', N'nchar', N'ntext')
THEN N'(' + CASE WHEN c.max_length = -1 THEN N'MAX' ELSE CAST(c.max_length / 2 AS NVARCHAR(5)) END + N')'
WHEN tp.name IN (N'datetime2', N'time2', N'datetimeoffset')
THEN N'(' + CAST(c.scale AS NVARCHAR(5)) + N')'
WHEN tp.name = N'decimal'
THEN N'(' + CAST(c.[precision] AS NVARCHAR(5)) + N',' + CAST(c.scale AS NVARCHAR(5)) + N')'
ELSE N''
END +
CASE WHEN c.collation_name IS NOT NULL and #GenerateCollation = 1 THEN N' COLLATE ' + c.collation_name ELSE N'' END +
CASE WHEN c.is_nullable = 1 THEN N' NULL' ELSE N' NOT NULL' END +
CASE WHEN dc.[definition] IS NOT NULL THEN CASE WHEN #GenerateConstraintNameOfDefaults = 1 THEN N' CONSTRAINT ' + quotename(dc.name) ELSE N'' END + N' DEFAULT' + dc.[definition] ELSE N'' END +
CASE WHEN ic.is_identity = 1 and #GenerateIdentity = 1 THEN N' IDENTITY(' + CAST(ISNULL(ic.seed_value, N'0') AS NCHAR(1)) + N',' + CAST(ISNULL(ic.increment_value, N'1') AS NCHAR(1)) + N')' ELSE N'' END
END + #CR
AS nvarchar(Max))
FROM sys.columns c WITH (NOWAIT)
INNER 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(N''), TYPE).value(N'.', N'NVARCHAR(MAX)'), 1, 2, #TB + N' ')
as nvarchar(max))
ELSE
CAST('' as nvarchar(max))
end
+
---------------------- Key Constraints ----------------------------------------------------------------
CAST(
case when #GenerateKeyConstraints <> 1 THEN N'' ELSE
ISNULL((SELECT #TB + N', CONSTRAINT ' + quotename(k.name) + N' PRIMARY KEY ' + ISNULL(kidx.type_desc, N'') + N'(' +
(SELECT STUFF((
SELECT N', ' + quotename(c.name) + N' ' + CASE WHEN ic.is_descending_key = 1 THEN N'DESC' ELSE N'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(N'.', N'NVARCHAR(MAX)'), 1, 2, N''))
+ N')' + #CR
FROM sys.key_constraints k WITH (NOWAIT) LEFT JOIN sys.indexes kidx ON
k.parent_object_id = kidx.object_id and k.unique_index_id = kidx.index_id
WHERE k.parent_object_id = #object_id
AND k.[type] = N'PK'), N'') + N')' + #CR
END
as nvarchar(max))
+
CAST(
CASE
WHEN
#GenerateDataCompressionOptions = 1
AND
(SELECT top 1 data_compression_desc from sys.partitions where object_ID = #object_id and index_id = 1) <> N'NONE'
THEN
N'WITH (DATA_COMPRESSION=' + (SELECT top 1 data_compression_desc from sys.partitions where object_ID = #object_id and index_id = 1) + N')' + #CR
ELSE
N'' + #CR
END as nvarchar(max))
+
--------------------- FOREIGN KEYS -----------------------------------------------------------------------------------------------------------------
CAST((CASE WHEN #GenerateMessages = 1 and #GenerateDropFKIfItExists = 1 THEN
N'RAISERROR(''CREATING FK OF %s'',10,1, ''' + quotename(OBJECT_schema_name(#object_id)) + N'.' + quotename(OBJECT_NAME(#object_id)) + N''') WITH NOWAIT;' + #CR
ELSE N'' END) as nvarchar(max))
+
CAST(
ISNULL((SELECT (
SELECT #CR +
N'ALTER TABLE ' + + quotename(OBJECT_schema_name(#object_id)) + N'.' + quotename(OBJECT_NAME(#object_id)) + + N' WITH'
+ CASE WHEN fk.is_not_trusted = 1
THEN N' NOCHECK'
ELSE N' CHECK'
END +
N' ADD CONSTRAINT ' + quotename(fk.name) + N' FOREIGN KEY('
+ STUFF((
SELECT N', ' + quotename(k.cname) + N''
FROM fk_columns k
WHERE k.constraint_object_id = fk.[object_id]
FOR XML PATH(N''), TYPE).value(N'.', N'NVARCHAR(MAX)'), 1, 2, N'')
+ N')' +
N' REFERENCES ' + quotename(SCHEMA_NAME(ro.[schema_id])) + N'.' + quotename(ro.name) + N' ('
+ STUFF((
SELECT N', ' + quotename(k.rcname) + N''
FROM fk_columns k
WHERE k.constraint_object_id = fk.[object_id]
FOR XML PATH(N''), TYPE).value(N'.', N'NVARCHAR(MAX)'), 1, 2, N'')
+ N')'
+ CASE
WHEN fk.delete_referential_action = 1 THEN N' ON DELETE CASCADE'
WHEN fk.delete_referential_action = 2 THEN N' ON DELETE SET NULL'
WHEN fk.delete_referential_action = 3 THEN N' ON DELETE SET DEFAULT'
ELSE N''
END
+ CASE
WHEN fk.update_referential_action = 1 THEN N' ON UPDATE CASCADE'
WHEN fk.update_referential_action = 2 THEN N' ON UPDATE SET NULL'
WHEN fk.update_referential_action = 3 THEN N' ON UPDATE SET DEFAULT'
ELSE N''
END
+ #CR + N'ALTER TABLE ' + + quotename(OBJECT_schema_name(#object_id)) + N'.' + quotename(OBJECT_NAME(#object_id)) + + N' CHECK CONSTRAINT ' + quotename(fk.name) + N'' + #CR
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(N'.', N'NVARCHAR(MAX)')), N'')
as nvarchar(max))
+
--------------------- INDEXES ----------------------------------------------------------------------------------------------------------
CAST((CASE WHEN #GenerateMessages = 1 and #GenerateIndexes = 1 THEN
N'RAISERROR(''CREATING INDEXES OF %s'',10,1, ''' + quotename(OBJECT_schema_name(#object_id)) + N'.' + quotename(OBJECT_NAME(#object_id)) + N''') WITH NOWAIT;' + #CR
ELSE N'' END) as nvarchar(max))
+
case when #GenerateIndexes = 1 THEN
CAST(
ISNULL(((SELECT
#CR + N'CREATE' + CASE WHEN i.is_unique = 1 THEN N' UNIQUE ' ELSE N' ' END
+ i.type_desc + N' INDEX ' + quotename(i.name) + N' ON ' + + quotename(OBJECT_schema_name(#object_id)) + N'.' + quotename(OBJECT_NAME(#object_id)) + + N' (' +
STUFF((
SELECT N', ' + quotename(c.name) + N'' + CASE WHEN c.is_descending_key = 1 THEN N' DESC' ELSE N' ASC' END
FROM index_column c
WHERE c.is_included_column = 0
AND c.index_id = i.index_id
FOR XML PATH(N''), TYPE).value(N'.', N'NVARCHAR(MAX)'), 1, 2, N'') + N')'
+ ISNULL(#CR + N'INCLUDE (' +
STUFF((
SELECT N', ' + quotename(c.name) + N''
FROM index_column c
WHERE c.is_included_column = 1
AND c.index_id = i.index_id
FOR XML PATH(N''), TYPE).value(N'.', N'NVARCHAR(MAX)'), 1, 2, N'') + N')', N'') + #CR
FROM sys.indexes i WITH (NOWAIT)
WHERE i.[object_id] = #object_id
AND i.is_primary_key = 0
AND i.[type] in (1,2)
and #GenerateIndexes = 1
FOR XML PATH(N''), TYPE).value(N'.', N'NVARCHAR(MAX)')
), N'')
as nvarchar(max))
ELSE
CAST(N'' as nvarchar(max))
END
+
------------------------ #GenerateDelete ----------------------------------------------------------
CAST((CASE WHEN #GenerateMessages = 1 and #GenerateDelete = 1 THEN
N'RAISERROR(''TRUNCATING %s'',10,1, ''' + quotename(OBJECT_schema_name(#object_id)) + N'.' + quotename(OBJECT_NAME(#object_id)) + N''') WITH NOWAIT;' + #CR
ELSE N'' END) as nvarchar(max))
+
CASE WHEN #GenerateDelete = 1 THEN
CAST(
(CASE WHEN exists (SELECT * FROM sys.foreign_keys WHERE referenced_object_id = #object_id) THEN
N'DELETE FROM ' + quotename(OBJECT_schema_name(#object_id)) + N'.' + quotename(OBJECT_NAME(#object_id)) + N';' + #CR
ELSE
N'TRUNCATE TABLE ' + quotename(OBJECT_schema_name(#object_id)) + N'.' + quotename(OBJECT_NAME(#object_id)) + N';' + #CR
END)
AS NVARCHAR(max))
ELSE
CAST(N'' as nvarchar(max))
END
+
------------------------- #GenerateInsertInto ----------------------------------------------------------
CAST((CASE WHEN #GenerateMessages = 1 and #GenerateDropFKIfItExists = 1 THEN
N'RAISERROR(''INSERTING INTO %s'',10,1, ''' + quotename(OBJECT_schema_name(#object_id)) + N'.' + quotename(OBJECT_NAME(#object_id)) + N''') WITH NOWAIT;' + #CR
ELSE N'' END) as nvarchar(max))
+
CASE WHEN #GenerateInsertInto = 1
THEN
CAST(
CASE WHEN EXISTS (SELECT * from sys.columns c where c.[object_id] = #object_id and is_identity = 1) AND #GenerateIdentityInsert = 1 THEN
N'SET IDENTITY_INSERT ' + quotename(OBJECT_schema_name(#object_id)) + N'.' + quotename(OBJECT_NAME(#object_id)) + N' ON;' + #CR
ELSE
CAST('' AS nvarchar(max))
END
+
N'INSERT INTO ' + QUOTENAME(#TargetDatabase) + N'.' + quotename(OBJECT_schema_name(#object_id)) + N'.' + quotename(OBJECT_NAME(#object_id)) + N'('
+ #CR
+
(
#TB + N' ' + SUBSTRING(
(
SELECT #TB + ','+ quotename(Name) + #CR
from sys.columns c
where
c.[object_id] = #object_id
AND system_type_ID <> 189 /*timestamp*/
AND is_computed = 0
and (is_identity = 0 or #GenerateIdentityInsert in (0,1))
FOR XML PATH(N''), TYPE).value(N'.', N'NVARCHAR(MAX)')
,3,99999)
)
+ N')' + #CR + N'SELECT '
+ #CR
+
(
#TB + N' ' + SUBSTRING(
(
SELECT #TB + ','+ quotename(Name) + #CR
FROM sys.columns c
WHERE c.[object_id] = #object_id
and system_type_ID <> 189 /*timestamp*/
and is_computed = 0
and (is_identity = 0 or #GenerateIdentityInsert in (0,1))
FOR XML PATH(N''), TYPE).value(N'.', N'NVARCHAR(MAX)')
,3,99999)
)
+ N'FROM ' + #SourceDatabase + N'.' + quotename(OBJECT_schema_name(#object_id)) + N'.' + quotename(OBJECT_NAME(#object_id))
+ N';' + #CR
+ CASE WHEN EXISTS (SELECT * from sys.columns c where c.[object_id] = #object_id and is_identity = 1) AND #GenerateIdentityInsert = 1 THEN
N'SET IDENTITY_INSERT ' + quotename(OBJECT_schema_name(#object_id)) + N'.' + quotename(OBJECT_NAME(#object_id)) + N' OFF;'+ #CR
ELSE
CAST('' AS nvarchar(max))
END
as nvarchar(max))
ELSE
CAST(
N''
as nvarchar(max))
END
+
-------------------- USE TRANSACTION --------------------------------------------------------------------------------------------------
CAST(
CASE WHEN #UseTransaction = 1
THEN
#CR + N'COMMIT TRAN; '
+ #CR + N'END TRY'
+ #CR + N'BEGIN CATCH'
+ #CR + N' IF XACT_STATE() IN (-1,1)'
+ #CR + N' ROLLBACK TRAN;'
+ #CR + N''
+ #CR + N' SELECT ERROR_NUMBER() AS ErrorNumber '
+ #CR + N' ,ERROR_SEVERITY() AS ErrorSeverity '
+ #CR + N' ,ERROR_STATE() AS ErrorState '
+ #CR + N' ,ERROR_PROCEDURE() AS ErrorProcedure '
+ #CR + N' ,ERROR_LINE() AS ErrorLine '
+ #CR + N' ,ERROR_MESSAGE() AS ErrorMessage; '
+ #CR + N'END CATCH'
ELSE N'' END
as nvarchar(max))
--print is limited to 4000 chars, if necessary, I use multiple print
--to maintain the consistency of the script, I split near the closest CrLF to the max chunk size
DECLARE #i int = 1;
DECLARE #maxChunk integer = 3990;
DECLARE #len integer = #maxChunk;
WHILE #i < len(#SQL)
BEGIN
IF len(#SQL) > (#i + #len)
set #len = len(substring(#SQL, #i, #maxChunk)) - CHARINDEX(#CR, reverse(substring(#SQL, #i, #len))) + 1
PRINT substring(#SQL, #i, #len)
set #i = #i + #len
set #len = #maxChunk
END
--SELECT datalength(#SQL), #sql
--EXEC sys.sp_executesql #SQL
goto backFromCreateScript;
"Easiest way is to use the built-in feature of SQL Management Studio"
but...
I have resolved it with a function and a couple of procedures.
For example, to obtain the create table for a table named 'table_name', you have to execute just the procedure called sp_ppinScriptTabla:
Exec sp_ppinScriptTabla 'table_name'
Here is the tsql script code:
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
Try sp_helptext Equivalent for Tables?
https://www.sqlservercentral.com/forums/topic/script-create-table-script-from-linked-server
For Linked Servers - on SQL Server - following works great -
SELECT *
INTO MyNewTable
FROM MyLinkedServer.DatabaseName.dbo.TargetTable
WHERE 1 = 0
--no data transferred, but the table gets built.
You forgot to include the stored procedure or function script for sp_ppinCamposIndice
Here's a slight variation on #Devart 's answer so you can get the CREATE script for a temp table.
Please note that since the #SQL variable is an NVARCHAR(MAX) data type you might not be able to copy it from the result using just only SSMS. Please see this question to see how to get the full value of a MAX field.
DECLARE #temptable_objectid INT = OBJECT_ID('tempdb..#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
Easiest way is to use the built-in feature of SQL Management Studio.
Right-click the database, go to tasks, Generate Scripts, and walk through the wizard. You can choose what objects to script, and it'll make it all for you.
Now if you are trying to make your OWN script to do the same thing, you're probably up for a lot of work...
Since we're offering alternatives to what you asked..
If you're in .Net, you should look at the Database Publishing Wizard in Visual Studio. Easy way to script your tables/data to a text file.
http://www.codeplex.com/sqlhost/Wiki/View.aspx?title=Database%20Publishing%20Wizard
Use the SSMS, easiest way
You can configure options for it as well (eg collation, syntax, drop...create)
Otherwise, SSMS Tools Pack, or DbFriend on CodePlex can help you generate scripts
See my answer in this Question : How to generate create script of table using SQL query in SQL Server
Use this query :
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
And you can fire this Function like this :
Select [dbo].Get_Table_Script '<Your_Table_Name>'
Try this (using "Results to text"):
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: Check constraint
D: Default constraint
F: Foreign Key constraint
L: Log
P: Stored procedure
PK: Primary Key constraint
RF: Replication Filter stored procedure
S: System table
TR: Trigger
U: User table
UQ: Unique constraint
V: View
X: Extended stored procedure
Cheers,
we can let the SQL to generate create table script by navigating as
Script Table as > CREATE To > New Query Editor Window
#Devart : Thank you,The answer was perfect, I'm adding something which I found while coding.
#ildanny : Thank you for removing the word limitation
my inferences:
Added Default and Check constraints
Changed Identity :
varchar(max) from char(1) : some tables may start from large numbers
Triggers can also be added as they are part of table, the definition
is directly available from select object_id from sys.triggers'
.
.
.
CASE WHEN dc.[definition] IS NOT NULL THEN ' CONSTRAINT ' + quotename(dc.name) + ' DEFAULT' + dc.[definition] ELSE '' END +
CASE WHEN ck.[definition] IS NOT NULL THEN ' CONSTRAINT ' + quotename(ck.name) + ' CHECK' + ck.[definition] ELSE '' END +
CASE WHEN ic.is_identity = 1 THEN ' IDENTITY(' + CAST(ISNULL(ic.seed_value, '0') AS VARCHAR) + ',' + CAST(ISNULL(ic.increment_value, '1') AS VARCHAR) + ')' ELSE '' END
.
.
.
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.check_constraints ck WITH (NOWAIT) ON c.[object_id] = ck.parent_object_id AND c.column_id = ck.parent_column_id
.
.
.
Expanding on #Devart and #ildanny solutions...
I had the need to run this for ALL tables in a db and also to execute the code against Linked Servers.
All tables...
/*
Ex.
EXEC etl.GetTableDefinitions '{friendlyname}', '{DatabaseName}', 'All', 0, NULL;
EXEC etl.GetTableDefinitions '{friendlyname}', '{DatabaseName}', 'dbo', 0, NULL;
EXEC etl.GetTableDefinitions '{friendlyname}', '{DatabaseName}', 'All', 1, '{linkedservername}';
*/
CREATE PROCEDURE etl.GetTableDefinitions
(
#SystemName NVARCHAR(128)
, #DatabaseName NVARCHAR(128)
, #SchemaName NVARCHAR(128)
, #linkedserver BIT
, #linkedservername NVARCHAR(128)
)
AS
DECLARE #sql NVARCHAR(MAX) = N'';
DECLARE #sql1 NVARCHAR(MAX) = N'';
DECLARE #inSchemaName NVARCHAR(MAX) = N'';
SELECT #inSchemaName = CASE WHEN #SchemaName = N'All' THEN N's.[name]' ELSE '''' + #SchemaName + '''' END;
IF #linkedserver = 0
BEGIN
SELECT #sql = N'
SET NOCOUNT ON;
--- options ---
DECLARE #UseTransaction BIT = 0;
DECLARE #GenerateUseDatabase BIT = 0;
DECLARE #GenerateFKs BIT = 0;
DECLARE #GenerateIdentity BIT = 1;
DECLARE #GenerateCollation BIT = 0;
DECLARE #GenerateCreateTable BIT = 1;
DECLARE #GenerateIndexes BIT = 0;
DECLARE #GenerateConstraints BIT = 1;
DECLARE #GenerateKeyConstraints BIT = 1;
DECLARE #GenerateConstraintNameOfDefaults BIT = 1;
DECLARE #GenerateDropIfItExists BIT = 0;
DECLARE #GenerateDropFKIfItExists BIT = 0;
DECLARE #GenerateDelete BIT = 0;
DECLARE #GenerateInsertInto BIT = 0;
DECLARE #GenerateIdentityInsert INT = 0; --0 ignore set,but add column; 1 generate; 2 ignore set AND column
DECLARE #GenerateSetNoCount INT = 0; --0 ignore set,1=set on, 2=set off
DECLARE #GenerateMessages BIT = 0; --print with no wait
DECLARE #GenerateDataCompressionOptions BIT = 0; --TODO: generates the compression option only of the TABLE, not the indexes
--NB: the compression options reflects the design VALUE.
--The actual compression of a the page is saved here
--- variables ---
DECLARE #DataTypeSpacer INT = 1; --this is just to improve the formatting of the script ...
DECLARE #name SYSNAME;
DECLARE #sql NVARCHAR(MAX) = N'''';
DECLARE #int INT = 1;
DECLARE #maxint INT;
DECLARE #SourceDatabase NVARCHAR(MAX) = N''' + #DatabaseName + '''; --this is used by the INSERT
DECLARE #TargetDatabase NVARCHAR(MAX) = N''' + #DatabaseName + '''; --this is used by the INSERT AND USE <DBName>
DECLARE #cr NVARCHAR(20) = NCHAR(13);
DECLARE #tab NVARCHAR(20) = NCHAR(9);
DECLARE #Tables TABLE
(
id INT IDENTITY(1,1)
, [name] SYSNAME
, [object_id] INT
, [database_id] SMALLINT
);
BEGIN
INSERT INTO #Tables([name], [object_id], [database_id])
SELECT s.[name] + N''.'' + t.[name] AS [name]
, t.[object_id]
, DB_ID(''' + #DatabaseName + ''') AS [database_id]
FROM [' + #DatabaseName + '].sys.tables t
JOIN [' + #DatabaseName + '].sys.schemas s ON t.[schema_id] = s.[schema_id]
WHERE t.[name] NOT IN (''Tally'',''LOC_AND_SEG_CAP1'',''LOC_AND_SEG_CAP2'',''LOC_AND_SEG_CAP3'',''LOC_AND_SEG_CAP4'',''TableNames'')
AND s.[name] = ' + #inSchemaName + '
ORDER BY s.[name], t.[name];
SELECT #maxint = COUNT(0)
FROM #Tables;
WHILE #int <= #maxint
BEGIN
;WITH
index_column AS
(
SELECT ic.[object_id]
, OBJECT_NAME(ic.[object_id], DB_ID(N''' + #DatabaseName + ''')) AS ObjectName
, ic.index_id
, ic.is_descending_key
, ic.is_included_column
, c.[name]
FROM [' + #DatabaseName + '].sys.index_columns ic WITH (NOLOCK)
JOIN [' + #DatabaseName + '].sys.columns c WITH (NOLOCK) ON ic.[object_id] = c.[object_id]
AND ic.column_id = c.column_id
JOIN [' + #DatabaseName + '].sys.tables t ON c.[object_id] = t.[object_id]
)
, fk_columns AS
(
SELECT k.constraint_object_id
, cname = c.[name]
, rcname = rc.[name]
FROM [' + #DatabaseName + '].sys.foreign_key_columns k WITH (NOWAIT)
JOIN [' + #DatabaseName + '].sys.columns rc WITH (NOWAIT) ON rc.[object_id] = k.referenced_object_id
AND rc.column_id = k.referenced_column_id
JOIN [' + #DatabaseName + '].sys.columns c WITH (NOWAIT) ON c.[object_id] = k.parent_object_id
AND c.column_id = k.parent_column_id
JOIN [' + #DatabaseName + '].sys.tables t ON c.[object_id] = t.[object_id]
WHERE #GenerateFKs = 1
)
SELECT #sql = #sql +
-------------------- USE DATABASE --------------------------------------------------------------------------------------------------
CAST(
CASE WHEN #GenerateUseDatabase = 1
THEN N''USE '' + #TargetDatabase + N'';'' + #cr
ELSE N'''' END
AS NVARCHAR(200))
+
-------------------- SET NOCOUNT --------------------------------------------------------------------------------------------------
CAST(
CASE #GenerateSetNoCount
WHEN 1 THEN N''SET NOCOUNT ON;'' + #cr
WHEN 2 THEN N''SET NOCOUNT OFF;'' + #cr
ELSE N'''' END
AS NVARCHAR(MAX))
+
-------------------- USE TRANSACTION --------------------------------------------------------------------------------------------------
CAST(
CASE WHEN #UseTransaction = 1
THEN
N''SET XACT_ABORT ON'' + #cr
+ N''BEGIN TRY'' + #cr
+ N''BEGIN TRAN'' + #cr
ELSE N'''' END
AS NVARCHAR(MAX))
+
-------------------- DROP SYNONYM --------------------------------------------------------------------------------------------------
CASE WHEN #GenerateDropIfItExists = 1
THEN CAST(N''IF OBJECT_ID('''''' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'''''',''''SN'''') IS NOT NULL DROP SYNONYM '' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'';'' + #cr AS NVARCHAR(MAX))
ELSE CAST(N'''' AS NVARCHAR(MAX)) END
+
-------------------- DROP TABLE IF EXISTS --------------------------------------------------------------------------------------------------
CASE WHEN #GenerateDropIfItExists = 1
THEN
--Drop TABLE if EXISTS
CAST(N''IF OBJECT_ID('''''' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'''''',''''U'''') IS NOT NULL DROP TABLE '' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'';'' + #cr AS NVARCHAR(MAX))
+ #cr
ELSE N'''' END
+
-------------------- DROP CONSTRAINT IF EXISTS --------------------------------------------------------------------------------------------------
CAST((CASE WHEN #GenerateMessages = 1 AND #GenerateDropFKIfItExists = 1 THEN
N''RAISERROR(''''DROP CONSTRAINTS OF %s'''',10,1, '''''' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'''''') WITH NOWAIT;'' + #cr
ELSE N'''' END) AS NVARCHAR(MAX))
+
CASE WHEN #GenerateDropFKIfItExists = 1
THEN
--Drop foreign keys
ISNULL(((
SELECT
CAST(
N''ALTER TABLE '' + QUOTENAME(s.[name]) + N''.'' + QUOTENAME(t.[name]) + N'' DROP CONSTRAINT '' + RTRIM(f.[name]) + N'';'' + #cr
AS NVARCHAR(MAX))
FROM [' + #DatabaseName + '].sys.tables t
INNER JOIN [' + #DatabaseName + '].sys.foreign_keys f ON f.parent_object_id = t.[object_id]
INNER JOIN [' + #DatabaseName + '].sys.schemas s ON s.[schema_id] = f.[schema_id]
WHERE f.referenced_object_id = t.[object_id]
FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)''))
, N'''') + #cr
ELSE N'''' END
+
--------------------- CREATE TABLE -----------------------------------------------------------------------------------------------------------------
CAST((CASE WHEN #GenerateMessages = 1 THEN
N''RAISERROR(''''CREATE TABLE %s'''',10,1, '''''' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'''''') WITH NOWAIT;'' + #cr
ELSE CAST(N'''' AS NVARCHAR(MAX)) END) AS NVARCHAR(MAX))
+
CASE WHEN #GenerateCreateTable = 1 THEN
CAST(
N''CREATE TABLE '' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + #cr + N''('' + #cr + STUFF((
SELECT
CAST(
#tab + N'','' + QUOTENAME(c.[name]) + N'' '' + ISNULL(REPLICATE('' '',#DataTypeSpacer - LEN(QUOTENAME(c.[name]))),'''')
+
CASE WHEN c.is_computed = 1
THEN N'' AS '' + cc.[definition]
ELSE UPPER(tp.[name]) +
CASE WHEN tp.[name] IN (N''varchar'', N''char'', N''varbinary'', N''binary'', N''text'')
THEN N''('' + CASE WHEN c.max_length = -1 THEN N''MAX'' ELSE CAST(c.max_length AS NVARCHAR(5)) END + N'')''
WHEN tp.[name] IN (N''NVARCHAR'', N''nchar'', N''ntext'')
THEN N''('' + CASE WHEN c.max_length = -1 THEN N''MAX'' ELSE CAST(c.max_length / 2 AS NVARCHAR(5)) END + N'')''
WHEN tp.[name] IN (N''datetime2'', N''time2'', N''datetimeoffset'')
THEN N''('' + CAST(c.scale AS NVARCHAR(5)) + N'')''
WHEN tp.[name] = N''decimal''
THEN N''('' + CAST(c.[precision] AS NVARCHAR(5)) + N'','' + CAST(c.scale AS NVARCHAR(5)) + N'')''
ELSE N''''
END +
CASE WHEN c.collation_name IS NOT NULL AND #GenerateCollation = 1 THEN N'' COLLATE '' + c.collation_name ELSE N'''' END +
CASE WHEN c.is_nullable = 1 THEN N'' NULL'' ELSE N'' NOT NULL'' END +
CASE WHEN dc.[definition] IS NOT NULL THEN CASE WHEN #GenerateConstraintNameOfDefaults = 1 THEN N'' CONSTRAINT '' + QUOTENAME(dc.[name]) ELSE N'''' END + N'' DEFAULT'' + dc.[definition] ELSE N'''' END +
CASE WHEN ic.is_identity = 1 AND #GenerateIdentity = 1 THEN N'' IDENTITY('' + CAST(ISNULL(ic.seed_value, N''0'') AS NCHAR(1)) + N'','' + CAST(ISNULL(ic.increment_value, N''1'') AS NCHAR(1)) + N'')'' ELSE N'''' END
END + #cr
AS NVARCHAR(MAX))
FROM [' + #DatabaseName + '].sys.columns c WITH (NOWAIT)
INNER JOIN [' + #DatabaseName + '].sys.types tp WITH (NOWAIT) ON c.user_type_id = tp.user_type_id
LEFT JOIN [' + #DatabaseName + '].sys.computed_columns cc WITH (NOWAIT) ON c.[object_id] = cc.[object_id]
AND c.column_id = cc.column_id
LEFT JOIN [' + #DatabaseName + '].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 [' + #DatabaseName + '].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] = t.[object_id]
ORDER BY c.column_id
FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)''), 1, 2, #tab + N'' '') AS NVARCHAR(MAX))
ELSE CAST(N'''' AS NVARCHAR(MAX)) END
+
---------------------- Key Constraints ----------------------------------------------------------------
CAST(
CASE WHEN #GenerateKeyConstraints <> 1 THEN N''''
ELSE
ISNULL((SELECT #tab + N'', CONSTRAINT '' + QUOTENAME(k.[name]) + N'' PRIMARY KEY '' + ISNULL(kidx.[type_desc], N'''') + N''('' +
(SELECT STUFF((
SELECT N'', '' + QUOTENAME(c.[name]) + N'' '' + CASE WHEN ic.is_descending_key = 1 THEN N''DESC'' ELSE N''ASC'' END
FROM [' + #DatabaseName + '].sys.index_columns ic WITH (NOWAIT)
JOIN [' + #DatabaseName + '].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(N''.'', N''NVARCHAR(MAX)''), 1, 2, N''''))
+ N'')'' + #cr
FROM [' + #DatabaseName + '].sys.key_constraints k WITH (NOWAIT)
LEFT JOIN [' + #DatabaseName + '].sys.indexes kidx ON k.parent_object_id = kidx.[object_id]
AND k.unique_index_id = kidx.index_id
WHERE k.parent_object_id = t.[object_id]
AND k.[type] = N''PK''), N'''') + N'')'' + #cr
END
AS NVARCHAR(MAX))
+
CAST(
CASE
WHEN #GenerateDataCompressionOptions = 1 AND (SELECT TOP 1 data_compression_desc FROM [' + #DatabaseName + '].sys.partitions WHERE OBJECT_ID = t.[object_id] AND index_id = 1) <> N''NONE''
THEN N''WITH (DATA_COMPRESSION='' + (SELECT TOP 1 data_compression_desc FROM [' + #DatabaseName + '].sys.partitions WHERE OBJECT_ID = t.[object_id] AND index_id = 1) + N'')'' + #cr
ELSE N'''' + #cr
END AS NVARCHAR(MAX))
+
--------------------- FOREIGN KEYS -----------------------------------------------------------------------------------------------------------------
CAST((CASE WHEN #GenerateMessages = 1 AND #GenerateDropFKIfItExists = 1 THEN
N''RAISERROR(''''CREATING FK OF %s'''',10,1, '''''' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'''''') WITH NOWAIT;'' + #cr
ELSE N'''' END) AS NVARCHAR(MAX))
+
CAST(
ISNULL((SELECT (
SELECT #cr +
N''ALTER TABLE '' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'' WITH''
+ CASE WHEN fk.is_not_trusted = 1
THEN N'' NOCHECK''
ELSE N'' CHECK''
END +
N'' ADD CONSTRAINT '' + QUOTENAME(fk.[name]) + N'' FOREIGN KEY(''
+ STUFF((
SELECT N'', '' + QUOTENAME(k.cname) + N''''
FROM fk_columns k
WHERE k.constraint_object_id = fk.[object_id]
AND fk.[object_id] = t.[object_id]
FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)''), 1, 2, N'''')
+ N'')'' +
N'' REFERENCES '' + QUOTENAME(SCHEMA_NAME(ro.[schema_id])) + N''.'' + QUOTENAME(ro.[name]) + N'' (''
+ STUFF((
SELECT N'', '' + QUOTENAME(k.rcname) + N''''
FROM fk_columns k
WHERE k.constraint_object_id = fk.[object_id]
AND fk.[object_id] = t.[object_id]
FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)''), 1, 2, N'''')
+ N'')''
+ CASE
WHEN fk.delete_referential_action = 1 THEN N'' ON DELETE CASCADE''
WHEN fk.delete_referential_action = 2 THEN N'' ON DELETE SET NULL''
WHEN fk.delete_referential_action = 3 THEN N'' ON DELETE SET DEFAULT''
ELSE N''''
END
+ CASE
WHEN fk.update_referential_action = 1 THEN N'' ON UPDATE CASCADE''
WHEN fk.update_referential_action = 2 THEN N'' ON UPDATE SET NULL''
WHEN fk.update_referential_action = 3 THEN N'' ON UPDATE SET DEFAULT''
ELSE N''''
END
+ #cr + N''ALTER TABLE '' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'' CHECK CONSTRAINT '' + QUOTENAME(fk.[name]) + N'''' + #cr
FROM [' + #DatabaseName + '].sys.foreign_keys fk WITH (NOWAIT)
JOIN [' + #DatabaseName + '].sys.objects ro WITH (NOWAIT) ON ro.[object_id] = fk.referenced_object_id
WHERE fk.parent_object_id = t.[object_id]
FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)'')), N'''')
AS NVARCHAR(MAX))
+
--------------------- INDEXES ----------------------------------------------------------------------------------------------------------
CAST((CASE WHEN #GenerateMessages = 1 AND #GenerateIndexes = 1 THEN
N''RAISERROR(''''CREATING INDEXES OF %s'''',10,1, '''''' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'''''') WITH NOWAIT;'' + #cr
ELSE N'''' END) AS NVARCHAR(MAX))
+
CASE WHEN #GenerateIndexes = 1 THEN
CAST(
ISNULL(((SELECT
#cr + N''CREATE'' + CASE WHEN i.is_unique = 1 THEN N'' UNIQUE '' ELSE N'' '' END
+ i.[type_desc] + N'' INDEX '' + QUOTENAME(i.[name]) + N'' ON '' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'' ('' +
STUFF((
SELECT N'', '' + QUOTENAME(c.[name]) + N'''' + CASE WHEN c.is_descending_key = 1 THEN N'' DESC'' ELSE N'' ASC'' END
FROM index_column c
WHERE c.is_included_column = 0
AND c.[object_id] = t.[object_id]
AND c.index_id = i.index_id
FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)''), 1, 2, N'''') + N'')''
+ ISNULL(#cr + N''INCLUDE ('' +
STUFF((
SELECT N'', '' + QUOTENAME(c.[name]) + N''''
FROM index_column c
WHERE c.is_included_column = 1
AND c.[object_id] = t.[object_id]
AND c.index_id = i.index_id
FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)''), 1, 2, N'''') + N'')'', N'''') + #cr
FROM [' + #DatabaseName + '].sys.indexes i WITH (NOWAIT)
WHERE i.[object_id] = t.[object_id]
AND i.is_primary_key = 0
AND i.[type] in (1,2)
AND #GenerateIndexes = 1
FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)'')
), N'''')
AS NVARCHAR(MAX))
ELSE N'''' END
+
------------------------ #GenerateDelete ----------------------------------------------------------
CAST((CASE WHEN #GenerateMessages = 1 AND #GenerateDelete = 1 THEN
N''RAISERROR(''''TRUNCATING %s'''',10,1, '''''' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'''''') WITH NOWAIT;'' + #cr
ELSE N'''' END) AS NVARCHAR(MAX))
+
CASE WHEN #GenerateDelete = 1 THEN
CAST(
(CASE WHEN EXISTS (SELECT TOP 1 [name] FROM [' + #DatabaseName + '].sys.foreign_keys WHERE referenced_object_id = t.[object_id]) THEN
N''DELETE FROM '' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'';'' + #cr
ELSE
N''TRUNCATE TABLE '' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'';'' + #cr
END)
AS NVARCHAR(MAX))
ELSE N'''' END
+
------------------------- #GenerateInsertInto ----------------------------------------------------------
CAST((CASE WHEN #GenerateMessages = 1 AND #GenerateDropFKIfItExists = 1 THEN
N''RAISERROR(''''INSERTING INTO %s'''',10,1, '''''' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'''''') WITH NOWAIT;'' + #cr
ELSE N'''' END) AS NVARCHAR(MAX))
+
CASE WHEN #GenerateInsertInto = 1
THEN
CAST(
CASE WHEN EXISTS (SELECT TOP 1 c.[name] FROM [' + #DatabaseName + '].sys.columns c WHERE c.[object_id] = t.[object_id] AND c.is_identity = 1) AND #GenerateIdentityInsert = 1 THEN
N''SET IDENTITY_INSERT '' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'' ON;'' + #cr
ELSE N'''' END
+
N''INSERT INTO '' + QUOTENAME(#TargetDatabase) + N''.'' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N''(''
+ #cr
+
(
#tab + N'' '' + SUBSTRING(
(
SELECT #tab + '',''+ QUOTENAME(c.[name]) + #cr
FROM [' + #DatabaseName + '].sys.columns c
WHERE c.[object_id] = t.[object_id]
AND c.system_type_ID <> 189 /*timestamp*/
AND c.is_computed = 0
AND (c.is_identity = 0 or #GenerateIdentityInsert in (0,1))
FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)'')
,3,99999)
)
+ N'')'' + #cr + N''SELECT ''
+ #cr
+
(
#tab + N'' '' + SUBSTRING(
(
SELECT #tab + '',''+ QUOTENAME(c.[name]) + #cr
FROM [' + #DatabaseName + '].sys.columns c
WHERE c.[object_id] = t.[object_id]
AND c.system_type_ID <> 189 /*timestamp*/
AND c.is_computed = 0
AND (c.is_identity = 0 or #GenerateIdentityInsert in (0,1))
FOR XML PATH(N''''), TYPE).value(N''.'', N''NVARCHAR(MAX)'')
,3,99999)
)
+ N''FROM '' + #SourceDatabase + N''.'' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id]))
+ N'';'' + #cr
+ CASE WHEN EXISTS (SELECT TOP 1 c.[name] FROM [' + #DatabaseName + '].sys.columns c WHERE c.[object_id] = t.[object_id] AND c.is_identity = 1) AND #GenerateIdentityInsert = 1 THEN
N''SET IDENTITY_INSERT '' + QUOTENAME(OBJECT_SCHEMA_NAME(t.[object_id], t.[database_id])) + N''.'' + QUOTENAME(OBJECT_NAME(t.[object_id], t.[database_id])) + N'' OFF;''+ #cr
ELSE N'''' END
AS NVARCHAR(MAX))
ELSE N'''' END
+
-------------------- USE TRANSACTION --------------------------------------------------------------------------------------------------
CAST(
CASE WHEN #UseTransaction = 1
THEN
#cr + N''COMMIT TRAN; ''
+ #cr + N''END TRY''
+ #cr + N''BEGIN CATCH''
+ #cr + N'' IF XACT_STATE() IN (-1,1)''
+ #cr + N'' ROLLBACK TRAN;''
+ #cr + N''''
+ #cr + N'' SELECT ERROR_NUMBER() AS ErrorNumber ''
+ #cr + N'' ,ERROR_SEVERITY() AS ErrorSeverity ''
+ #cr + N'' ,ERROR_STATE() AS ErrorState ''
+ #cr + N'' ,ERROR_PROCEDURE() AS ErrorProcedure ''
+ #cr + N'' ,ERROR_LINE() AS ErrorLine ''
+ #cr + N'' ,ERROR_MESSAGE() AS ErrorMessage; ''
+ #cr + N''END CATCH''
ELSE N'''' END
AS NVARCHAR(700))
FROM #Tables t
WHERE ID = #int
ORDER BY [name];
SET #int = #int + 1;
END
EXEC [master].dbo.PrintMax #sql;
/* see below for PrintMax code*/
END'
EXEC (#sql);
END
ELSE
And the Linked Server bit...
BEGIN
SELECT #sql = N'EXECUTE (''
SET NOCOUNT ON;
BEGIN
... Same code but be sure to double up on your single quotes
END
... code for the printmax proc (not mine, #Ben B) because it may not exist at destination server
DECLARE #CurrentEnd BIGINT; /* track the length of the next substring */
DECLARE #offset TINYINT; /*tracks the amount of offset needed */
DECLARE #String NVARCHAR(MAX);
SET #String = REPLACE(REPLACE(#sql, CHAR(13) + CHAR(10), CHAR(10)), CHAR(13), CHAR(10))
WHILE LEN(#String) > 1
BEGIN
IF CHARINDEX(CHAR(10), #String) BETWEEN 1 AND 4000
BEGIN
SET #CurrentEnd = CHARINDEX(CHAR(10), #String) -1
SET #offset = 2
END
ELSE
BEGIN
SET #CurrentEnd = 4000
SET #offset = 1
END
PRINT SUBSTRING(#String, 1, #CurrentEnd)
SET #String = SUBSTRING(#String, #CurrentEnd + #offset, LEN(#String))
END
END'') AT [' + #linkedservername + ']';
EXEC (#sql);
END
Ben B solution