TSQL |创建数据库

时间:2014-05-28 16:43:23

标签: sql sql-server tsql

我的本​​地有两个数据库。我希望使用tsql编写其完整(仅架构)中的两个数据库之一,并将其​​保存在一个.sql脚本中。这可能是SQL 2012吗?如果是这样,我该怎么做呢?我正在使用GUI来执行此操作但是如果可能的话想使用tsql查询。我无法使用任何第三方工具。

谢谢

更新:我正在使用右键单击>现在生成脚本方法。我想避免这种情况,并找到一种方法来生成数据库生成tsql脚本,而不是使用SSMS GUI。另外,我想编写整个数据库而不仅仅是表格。

1 个答案:

答案 0 :(得分:1)

您可以通过以下两种方式实现。

  1. 使用Powershell。
  2. 使用SMO类,特别是Scripter类。 GUI工具是这个类的包装器。
  3. 这是#1的解决方案。

    Using Powershell to Generate Table-Creation Scripts。在 simple-talk.com

    Robert Sheldon

    这是#2的解决方案。

    请参阅此MSDN Example scripting all tables in a database with SMO

    以下相关代码。根据需要更改数据库名称和其他详细信息。

    //Connect to the local, default instance of SQL Server. 
    { 
       Server srv = default(Server); 
       srv = new Server(); 
       //Reference the AdventureWorks database. 
       Database db = default(Database); 
       db = srv.Databases("AdventureWorks"); 
       //Define a Scripter object and set the required scripting options. 
       Scripter scrp = default(Scripter); 
       scrp = new Scripter(srv); 
       scrp.Options.ScriptDrops = false; 
       scrp.Options.WithDependencies = true; 
       //Iterate through the tables in database and script each one. Display the script. 
       //Note that the StringCollection type needs the System.Collections.Specialized namespace to be included. 
       Table tb = default(Table); 
       Urn[] smoObjects = new Urn[2]; 
       foreach ( tb in db.Tables) { 
          smoObjects = new Urn[1]; 
          smoObjects(0) = tb.Urn; 
          if (tb.IsSystemObject == false) { 
             StringCollection sc = default(StringCollection); 
             sc = scrp.Script(smoObjects); 
             string st = null; 
             foreach ( st in sc) { 
                Console.WriteLine(st); 
             } 
          } 
       } 
    } 
    

    如果要编写所有数据库对象的脚本,而不仅仅是表格,请查看the powershell script in this page所说的"完整脚本"。它还会处理表和关系依赖关系。