Click here to Skip to main content
15,889,867 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,
Instead of using Generate Scripts Wizard in SQL Server
Is there a way that I can generate scripts for tables dynamically using Stored procedure.

Thanks & Regards,
Mathi
Posted

You can use this [Tool] called ExportSQLScript to export MS SQL objects to script files suitable for database creation.
 
Share this answer
 
Comments
Mathi2code 1-Aug-13 8:18am    
Thanks Sudhakar
You may be Interested in these Sp's... I Suggest the First Stored Procedure..
Sp_generate_inserts.txt[^]
Sql Server Create Generate Script Sp[^]
 
Share this answer
 
v2
Comments
Mathi2code 1-Aug-13 8:18am    
Thanks Raja sekhar
Raja Sekhar S 1-Aug-13 8:22am    
You are Welcome... Glad to Help...
Hi,
The below code was also useful for resolving my requirement...


SQL
CREATE proc GetTableScript (@table sysname)
as
declare @sql table(s varchar(1000), id int identity)


insert into  @sql(s) values ('create table [' + @table + '] (')


insert into @sql(s)
select
    '  ['+column_name+'] ' +
    data_type + coalesce('('+cast(character_maximum_length as varchar)+')','') + ' ' +
    case when exists (
        select id from syscolumns
        where object_name(id)=@table
        and name=column_name
        and columnproperty(id,name,'IsIdentity') = 1
    ) then
        'IDENTITY(' +
        cast(ident_seed(@table) as varchar) + ',' +
        cast(ident_incr(@table) as varchar) + ')'
    else ''
    end + ' ' +
    ( case when IS_NULLABLE = 'No' then 'NOT ' else '' end ) + 'NULL ' +
    coalesce('DEFAULT '+COLUMN_DEFAULT,'') + ','

 from information_schema.columns where table_name = @table
 order by ordinal_position


declare @pkname varchar(100)
select @pkname = constraint_name from information_schema.table_constraints
where table_name = @table and constraint_type='PRIMARY KEY'

if ( @pkname is not null ) begin
    insert into @sql(s) values('  PRIMARY KEY (')
    insert into @sql(s)
        select '   ['+COLUMN_NAME+'],' from information_schema.key_column_usage
        where constraint_name = @pkname
        order by ordinal_position

    update @sql set s=left(s,len(s)-1) where id=@@identity
    insert into @sql(s) values ('  )')
end
else begin

    update @sql set s=left(s,len(s)-1) where id=@@identity
end

insert into @sql(s) values( ')' )

select s from @sql order by id
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900