2008-11-08 27 views
4

我正在嘗試爲我正在使用的本地數據庫創建數據庫腳本工具。使用SMO獲取表默認值的創建腳本

我已經能夠爲表,主鍵,索引和外鍵生成創建腳本,但我找不到任何方法爲表默認值生成創建腳本。

對於指數,它是那麼容易,因爲

foreach (Index index in table.Indexes) 
{ 
    ScriptingOptions drop = new ScriptingOptions(); 
    drop.ScriptDrops = true; 
    drop.IncludeIfNotExists = true; 

    foreach (string dropstring in index.Script(drop)) 
    { 
     createScript.Append(dropstring); 
    } 

    ScriptingOptions create = new ScriptingOptions(); 
    create.IncludeIfNotExists = true; 

    foreach (string createstring in index.Script(create)) 
    { 
     createScript.Append(createstring); 
    } 
} 

但表對象不具有默認屬性。有沒有其他方式來爲表格默認值生成腳本?

回答

1

雖然我沒有使用SMO,但我查閱了MSDN,這裏是我發現的。

表具有一個Columns屬性(列集合),它應該引用每個列。
每列將有一個DefaultConstraint屬性。

這是你在找什麼?

5

嘗試使用Scripter對象與DriAll選項設置:

Server server = new Server(@".\SQLEXPRESS"); 
Database db = server.Databases["AdventureWorks"]; 
List<Urn> list = new List<Urn>(); 
DataTable dataTable = db.EnumObjects(DatabaseObjectTypes.Table); 
foreach (DataRow row in dataTable.Rows) 
{ 
    list.Add(new Urn((string)row["Urn"])); 
} 
Scripter scripter = new Scripter(); 
scripter.Server = server; 
scripter.Options.IncludeHeaders = true; 
scripter.Options.SchemaQualify = true; 
scripter.Options.SchemaQualifyForeignKeysReferences = true; 
scripter.Options.NoCollation = true; 
scripter.Options.DriAllConstraints = true; 
scripter.Options.DriAll = true; 
scripter.Options.DriAllKeys = true; 
scripter.Options.DriIndexes = true; 
scripter.Options.ClusteredIndexes = true; 
scripter.Options.NonClusteredIndexes = true; 
scripter.Options.ToFileOnly = true; 
scripter.Options.FileName = @"C:\tables.sql"; 
scripter.Script(list.ToArray()); 
+0

嗨帕維爾,如果我想爲表生成腳本。例如說:Production.Categories。我需要添加腳本嗎?謝謝 – Goldfish 2017-07-20 00:31:09

0

加入到帕維爾的答案。

我只需要獲取一個invidual表的腳本。 1.我想傳遞表模式名稱和表名作爲參數並生成腳本。 2.將腳本分配給變量而不是寫入文件。對於單個表

代碼:

/*get a particular table script only*/ 
Table myTable = db.Tables["TableName", "SchemaName"]; 
scripter.Script(new Urn[] { myTable.Urn}); 

寫腳本變量:

StringCollection sc = scripter.Script(new Urn[] { myTable.Urn }); 
foreach (string script in sc) 
{ 
    sb.AppendLine(); 
    sb.AppendLine("--create table"); 
    sb.Append(script + ";"); 
} 

我希望這將有助於未來的讀者。