既定値の作成、変更、および削除
SMO (SQL Server 管理オブジェクト) では、既定の制約は Default オブジェクトで表現します。
挿入する値を設定するには、Default オブジェクトの TextBody プロパティを使用します。挿入する値は、定数であっても、GETDATE() などの定数値を返す Transact-SQL ステートメントであってもかまいません。TextBody プロパティは、Alter メソッドを使用して変更することはできません。Default オブジェクトをいったん削除してから再作成する必要があります。
例
提供されているコード例を使用するには、アプリケーションを作成するプログラミング環境、プログラミング テンプレート、およびプログラミング言語を選択する必要があります。詳細については、「Visual Studio .NET で Visual Basic SMO プロジェクトを作成する方法」または「Visual Studio .NET で Visual C# SMO プロジェクトを作成する方法」を参照してください。
Visual Basic での既定値の作成、変更、および削除
このコード例では、シンプル テキストである既定値と Transact-SQL ステートメントである別の既定値を作成する方法を示します。既定値を列にアタッチするには BindToColumn メソッドを使用し、列からのデタッチには UnbindFromColumn メソッドを使用する必要があります。
'Connect to the local, default instance of SQL Server.
Dim srv As Server
srv = New Server
'Reference the AdventureWorks database.
Dim db As Database
db = srv.Databases("AdventureWorks")
'Define a Default object variable by supplying the parent database and the default name
'in the constructor.
Dim def As [Default]
def = New [Default](db, "Test_Default2")
'Set the TextHeader and TextBody properties that define the default.
def.TextHeader = "CREATE DEFAULT [Test_Default2] AS"
def.TextBody = "GetDate()"
'Create the default on the instance of SQL Server.
def.Create()
'Declare a Column object variable and reference a column in the AdventureWorks database.
Dim col As Column
col = db.Tables("SpecialOffer", "Sales").Columns("StartDate")
'Bind the default to the column.
def.BindToColumn("SpecialOffer", "StartDate", "Sales")
'Unbind the default from the column and remove it from the database.
def.UnbindFromColumn("SpecialOffer", "StartDate", "Sales")
def.Drop()
Visual C# での既定値の作成、変更、および削除
このコード例では、シンプル テキストである既定値と Transact-SQL ステートメントである別の既定値を作成する方法を示します。既定値を列にアタッチするには BindToColumn メソッドを使用し、列からのデタッチには UnbindFromColumn メソッドを使用する必要があります。
{
//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 Default object variable by supplying the parent database and the default name
//in the constructor.
Default def = default(Default);
def = new Default(db, "Test_Default2");
//Set the TextHeader and TextBody properties that define the default.
def.TextHeader = "CREATE DEFAULT [Test_Default2] AS";
def.TextBody = "GetDate()";
//Create the default on the instance of SQL Server.
def.Create();
//Declare a Column object variable and reference a column in the AdventureWorks database.
Column col = default(Column);
col = db.Tables("SpecialOffer", "Sales").Columns("StartDate");
//Bind the default to the column.
def.BindToColumn("SpecialOffer", "StartDate", "Sales");
//Unbind the default from the column and remove it from the database.
def.UnbindFromColumn("SpecialOffer", "StartDate", "Sales");
def.Drop();
}