Wednesday, July 2, 2014
SIMPLE T-SQL to generate create table scripts
just run this in the database you want to script out --- use "Results to Text" mode:
EXEC sp_msforeachtable 'SELECT ''Create table ?
('' UNION ALL
SELECT CASE WHEN rn > 1 THEN '' ,'' ELSE '' '' END + x
FROM (SELECT TOP 100 percent ''[''+COLUMN_NAME + ''] '' + DATA_TYPE
+ CASE WHEN DATA_TYPE IN (''varchar'',''char'') THEN ''('' + CAST(CHARACTER_MAXIMUM_LENGTH as varchar) + '')'' ELSE '''' END
+ '' ''+ case when IS_NULLABLE = ''YES'' THEN ''NULL'' ELSE ''NOT NULL'' END x
,ROW_NUMBER() OVER(ORDER BY COLUMNS.ORDINAL_POSITION) rn
FROM INFORMATION_SCHEMA.columns WHERE COLUMNS.TABLE_NAME = replace(replace(''?'',''[dbo].['',''''),'']'','''')
) x
UNION ALL
SELECT '')''
'
outputs runnable create table script
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment