共用方式為


處理資料類型

資料有許多類型和大小,例如已定義長度的字串、具有特定精確度的數字,或是使用者定義資料類型 (有自己的規則集合的另一個物件)。DataType 物件會分類資料的類型,好讓 Microsoft SQL Server 可正確加以處理。DataType 物件與可接受資料的物件有關聯。下列 SQL Server Management Objects (SMO) 物件可接受必須由 DataType 物件屬性所定義的資料:

接受資料之物件的 DataType 屬性可利用幾種方式來加以設定。

  • 使用預設建構函式,並明確指定 DataType 物件屬性。

  • 使用多載的建構函式,並將 DataType 屬性指定為參數。

  • 在物件建構函式中指定 DataType 為內嵌。

  • 使用 DataType 類別的其中一個靜態成員,例如 Int。事實上,這樣會傳回 DataType 物件的執行個體。

DataType 物件有好幾個屬性會定義資料的類型。例如,SqlDataType 屬性會指定 SQL Server 資料類型。代表 SQL Server 資料類型的常數值會列在 SqlDataType 列舉中。這是指像是 varchar、nchar、currency、integer、float 和 datetime 等資料類型。

當建立該資料類型時,必須為資料設定特定的屬性。例如,如果它是 nchar 類型,字串資料的長度必須在 Length 屬性中設定。這同樣適用於數值,您必須為數值指定有效位數及小數位數。

UserDefinedDataTypeUserDefinedType 資料類型指的是包含使用者定義之資料類型定義的物件。UserDefinedDataType 是根據 SqlDataType 列舉中的 SQL Server 資料類型。UserDefinedType 是根據 Microsoft .NET 資料類型。一般來說,這些代表特定類型的資料,資料庫會因為組織所定義的商務規則而經常重複使用這些資料。例如,儲存金錢數量和貨幣單位的資料類型對於處理多種貨幣的公司會很有幫助。

SqlDataType 列舉包含所有 SQL Server 支援之資料類型的清單。

範例

如果要使用所提供的任何程式碼範例,您必須選擇建立應用程式用的程式設計環境、程式設計範本,及程式設計語言。如需詳細資訊,請參閱《SQL Server 線上叢書》中的<如何:在 Visual Studio .NET 中建立 Visual Basic SMO 專案>或<如何:在 Visual Studio .NET 中建立 Visual C# SMO 專案>。

在 Visual Basic 中使用建構函式內的規格來建構 DataType 物件

此程式碼範例示範如何使用此建構函式來建立以不同 SQL Server 資料類型為根據的資料類型執行個體。

[!附註]

UserDefinedTypeUserDefinedDataType 和 XML 類型全都需要一個名稱值,才能識別此物件。

'Declare a DataType object variable and define the data type in the constructor.
Dim dt As DataType
'For the decimal data type the following two arguements specify precision, and scale.
dt = New DataType(SqlDataType.Decimal, 10, 2)

在 Visual C# 中使用建構函式內的規格來建構 DataType 物件

此程式碼範例示範如何使用此建構函式來建立以不同 SQL Server 資料類型為根據的資料類型執行個體。

[!附註]

UserDefinedTypeUserDefinedDataType 和 XML 類型全都需要一個名稱值,才能識別此物件。

{ 
//Declare a DataType object variable and define the data type in the constructor. 
DataType dt; 
//For the decimal data type the following two arguements specify precision, and scale. 
dt = new DataType(SqlDataType.Decimal, 10, 2); 
}

在 Visual Basic 中使用預設建構函式來建構 DataType 物件

此程式碼範例示範如何使用預設建構函式來建立以不同 SQL Server 資料類型為根據的資料類型執行個體。然後會使用這些屬性來指定資料類型。

注意UserDefinedTypeUserDefinedDataType 和 XML 類型全都需要一個名稱值,才能識別此物件。

'Declare and create a DataType object variable.
Dim dt As DataType
dt = New DataType
'Define the data type by setting the SqlDataType property.
dt.SqlDataType = SqlDataType.VarChar
'The VarChar data type requires a value for the MaximumLength property.
dt.MaximumLength = 100

在 Visual C# 中使用預設建構函式來建構 DataType 物件

此程式碼範例示範如何使用預設建構函式來建立以不同 SQL Server 資料類型為根據的資料類型執行個體。然後會使用這些屬性來指定資料類型。

注意UserDefinedTypeUserDefinedDataType 和 XML 類型全都需要一個名稱值,才能識別此物件。

{ 
//Declare and create a DataType object variable. 
DataType dt; 
dt = new DataType(); 
//Define the data type by setting the SqlDataType property. 
dt.SqlDataType = SqlDataType.VarChar; 
//The VarChar data type requires a value for the MaximumLength property. 
dt.MaximumLength = 100; 
}