3

I have a SQL Server database and whenever I want to make a backup of the database, first generate a Drop and Create Script of the DB. Because by this way I can make my database in every version of SQL Server. Regardless of the version and maintenance problems of SQL.

In the Generate and Publish Scripts window of SQL Server there is an Advanced Scripting Option, as shown below:

Advanced Scripting Options

Now, I would like a script from this window to reproduce script generator advanced options. In the other words, I want a script to make script generator of my database by my selected Advanced Options.

How can I do it?

Behzad
  • 3,502
  • 4
  • 36
  • 63

2 Answers2

2

You can use SQL Server Profiler to retrieve executing sqls in the specified instance.

[How to see executing batch sqls in the specified instance][1]

Behzad
  • 3,502
  • 4
  • 36
  • 63
Hossein POURAKBAR
  • 1,073
  • 2
  • 15
  • 33
0

Please refer to this How to generate SQL Table Script through query

Is this what you want?

declare @table varchar(100)
set @table = 'MyTable' -- set table name here
declare @sql table(s varchar(1000), id int identity)

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

-- column list
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

-- primary key
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
    -- remove trailing comma
    update @sql set s=left(s,len(s)-1) where id=@@identity
    insert into @sql(s) values ('  )')
end
else begin
    -- remove trailing comma
    update @sql set s=left(s,len(s)-1) where id=@@identity
end

-- closing bracket
insert into @sql(s) values( ')' )

-- result!
select s from @sql order by id
Webster
  • 1,113
  • 2
  • 19
  • 39
  • this is a way to create script, but my question is about create a advanced options script in Stable state of sql server. thanks for answer +1 – Behzad Feb 07 '16 at 16:54