-2

I need to copy several tables definition from one database to other database. I have found a way to generate create statement for every individual table that I need. However I cannot execute every 'create statement' that is generated. I expect that following script will recreate all table that match criteria in NEWDB database. However it didn't. It always recreate only one table instead of all tables that I need. I am not sql expert and I believe I am missing something here.

declare @sql varchar(8000)

select  @sql='create table [NEWDB].[' + OBJECT_SCHEMA_NAME(so.id) + '].[' + 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 so
cross apply
    (SELECT 
        '  ['+column_name+'] ' + 
        data_type + case data_type
            when 'sql_variant' then ''
            when 'text' then ''
            when 'ntext' then ''
            when 'xml' then ''
            when 'decimal' then '(' + cast(numeric_precision 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)
left join
    information_schema.table_constraints tc
on  tc.Table_name       = so.Name
AND tc.Constraint_Type  = 'PRIMARY KEY'
cross apply
    (select '[' + Column_Name + '], '
     FROM   information_schema.key_column_usage kcu
     WHERE  kcu.Constraint_Name = tc.Constraint_Name
     ORDER BY
        ORDINAL_POSITION
     FOR XML PATH('')) j (list)
where   xtype = 'U'
AND name    NOT IN ('dtproperties')
-- criteria
AND name like 'AUD_%'
order by OBJECT_SCHEMA_NAME(so.id),so.name

-- this execute one table only regardless how many table in actual result set 
exec (@sql)
4
  • 3
    why not use the built-in scripting functionality in SSMS? Commented Apr 21, 2014 at 6:57
  • If built-in scripting that you mean is right click the table, select script table as then select create to in SSMS, then it's mean I have to do that manually for every table that I need. I need to do bulk copy all tables that I need in one time. Commented Apr 21, 2014 at 7:04
  • Have you looked at what you are executing. It could be that you only build the create statement for one table. I see no string concatenation going on for each table. Commented Apr 21, 2014 at 8:24
  • Hi Mikael, it was the original question mean to be, which is how to generate and execute multiple create table statement above. However I have found solution for that requirement by using cursor. Commented Apr 21, 2014 at 8:32

1 Answer 1

2

SSMS supports scripting all schema (and optionally data as INSERTS) in 2k8:

Right click on a database and select Tasks->Generate Scripts...

Select All tables OR Pick the tables you require, Click Next.

....

See answer here: to "Script all data from SQL Server database"

That's a lot easier than trying to roll your own.

Sign up to request clarification or add additional context in comments.

3 Comments

Hi Mitch, I still prefer to do it programmatically. I have hundreds tables and need only some table that match criteria. Using this feature will need me check or uncheck tables manually. For now all I need is how above script can be executed for individual 'create statement' that is generated.
so script out every table, and apply matching criteria to this text file? If you want to do it programmatically, I would suggest doing it with C# and SMO
select statement above will generate 'create table' statement for all tables that match criteria. Above, I pass that 'create table' statement to @sql variable. What I need is to execute every 'create table' statement generated using exec t-sql stored procedure. However I know in sql we might not just iterate result set and execute it like in programming language. For now I need only plain scripting way instead of using SSMS.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.