【问题标题】:How to create "Script Generator Options" scripts in SQL Server?如何在 SQL Server 中创建“脚本生成器选项”脚本?
【发布时间】:2016-02-07 16:36:11
【问题描述】:

我有一个 SQL Server 数据库,每当我想备份数据库时,首先生成数据库的Drop and Create Script。因为通过这种方式,我可以在 SQL Server 的每个版本中创建我的数据库。不管SQL的版本和维护问题。

SQL ServerGenerate and Publish Scripts窗口中有一个Advanced Scripting Option,如下图:

现在,我想要一个来自该窗口的脚本来重现脚本生成器高级选项。换句话说,我想要一个脚本来通过我选择的高级选项生成我的数据库的脚本生成器。

我该怎么做?

【问题讨论】:

    标签: sql-server generate-scripts


    【解决方案1】:

    您可以使用 SQL Server Profiler 检索指定实例中正在执行的 sql。

    [

    【讨论】:

      【解决方案2】:

      请参考这个How to generate SQL Table Script through query

      这是你想要的吗?

      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
      

      【讨论】:

      • 这是一种创建脚本的方法,但我的问题是关于在 sql server 的稳定状态下创建高级选项脚本。感谢您的回答 +1
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-18
      • 2012-02-18
      • 2012-03-14
      • 2012-08-05
      • 1970-01-01
      • 2016-07-18
      • 2011-06-17
      相关资源
      最近更新 更多