分享方式:


使用資料類型

適用於:sql ServerAzure SQL 資料庫 Azure SQL 受控執行個體 Microsoft Fabric 中的 Azure Synapse Analytics SQL 資料庫

數據有許多類型和大小,例如具有定義長度的字串、具有特定精確度的數位,或屬於另一個具有其規則集之物件的使用者定義數據類型。 物件 DataType 會分類數據類型,以便Microsoft SQL Server 正確處理。 物件 DataType 與接受數據的對象相關聯。 下列 SQL Server 管理物件 (SMO) 物件接受物件屬性必須定義 DataType 的資料:

可透過數種方式設定接受數據的物件的 DataType 屬性。

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

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

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

  • 使用 類別的 DataType 其中一個靜態成員,例如 Int。這實際上會傳回 對象的實例 DataType

DataType物件有數個定義數據類型的屬性。 例如, SqlDataType 屬性會指定 SQL Server 數據類型。 代表 SQL Server 數據類型的 SqlDataType 常數值會列在 列舉中。 這是指 varchar、nchar、currencyintegerfloatdatetime數據類型。

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

UserDefinedDataTypeUserDefinedType 數據類型是指包含使用者所定義數據類型定義的物件。 UserDefinedDataType是以列舉中的 SqlDataType SQL Server 數據類型為基礎。 UserDefinedType是以 .NET 數據類型Microsoft為基礎。 一般而言,這些代表資料庫經常重複使用的特定類型數據,因為組織所定義的商務規則。 例如,儲存金額和貨幣分母的數據類型對於以多種貨幣交易的公司很有説明。

列舉 SqlDataType 包含所有 SQL Server 支援的數據類型清單。

範例

若要使用提供的任何程式代碼範例,您必須選擇程式設計環境、程式設計範本,以及用來建立應用程式的程式設計語言。 如需詳細資訊,請參閱 在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 arguments 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 arguments 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;   
}