SQL Server 資料類型對應

適用於: .NET Framework .NET .NET 標準

下載 ADO.NET

SQL Server 和 .NET Framework 是以不同的型別系統為基礎。 例如,.NET Framework Decimal 結構的最大小數點位數為 28,而 SQL Server decimal 和 numeric 資料型別的最大小數點位數為 38。 為了在讀取及寫入資料時維持資料完整性,SqlDataReader 提供 SQL Server 專屬的具型別存取子方法,可傳回 System.Data.SqlTypes 的物件,以及可傳回 .NET Framework 型別的存取子方法。 SQL Server 型別和 .NET Framework 型別也會由 DbType 和 SqlDbType 類別 (Class) 中的列舉型別 (Enumeration) 表示,而且您可以在指定 SqlParameter 資料型別時使用這些類別。

下表顯示推斷的 .NET Framework 類型、DbType 與 SqlDbType 列舉,以及 SqlDataReader 的存取子方法。

SQL Server Database Engine 類型 .NET Framework 類型 SqlDbType 列舉型別 SqlDataReader SqlTypes 型別化存取子 DbType 列舉 SqlDataReader DbType 型別存取子
Bigint Int64 BigInt GetSqlInt64 Int64 GetInt64
二進位 Byte[] VarBinary GetSqlBinary Binary GetBytes
位元 布林值 Bit GetSqlBoolean Boolean GetBoolean
Char 字串

Char[]
Char GetSqlString AnsiStringFixedLength,

String
GetString

GetChars
日期 1

(SQL Server 2008 及以後版本)
日期和時間 Date 1 GetSqlDateTime Date 1 GetDateTime
日期時間 日期時間 DateTime GetSqlDateTime DateTime GetDateTime
datetime2

(SQL Server 2008 及以後版本)
日期時間 DateTime2 無 DateTime2 GetDateTime
datetimeoffset

(SQL Server 2008 及以後版本)
DateTimeOffset DateTimeOffset 無 DateTimeOffset GetDateTimeOffset
十進位 Decimal Decimal GetSqlDecimal Decimal GetDecimal
FILESTREAM 屬性(varbinary(max)) Byte[] VarBinary GetSqlBytes Binary GetBytes
float 雙精度 Float GetSqlDouble Double GetDouble
圖片 Byte[] Binary GetSqlBinary Binary GetBytes
int Int32 Int GetSqlInt32 Int32 GetInt32
金錢 Decimal Money GetSqlMoney Decimal GetDecimal
NCHAR 字串

Char[]
NChar GetSqlString StringFixedLength GetString

GetChars
ntext 字串

Char[]
NText GetSqlString String GetString

GetChars
數值 Decimal Decimal GetSqlDecimal Decimal GetDecimal
nvarchar 字串

Char[]
NVarChar GetSqlString String GetString

GetChars
真實 單一 Real GetSqlSingle Single GetFloat
rowversion Byte[] Timestamp GetSqlBinary Binary GetBytes
smalldatetime 日期時間 DateTime GetSqlDateTime DateTime GetDateTime
smallint Int16 SmallInt GetSqlInt16 Int16 GetInt16
smallmoney Decimal SmallMoney GetSqlMoney Decimal GetDecimal
sql_variant 對象 2 Variant GetSqlValue 2 Object GetValue 2
收發簡訊 字串

Char[]
Text GetSqlString String GetString

GetChars
時間

(SQL Server 2008 及以後版本)
TimeSpan Time 無 Time GetDateTime
時間戳記 Byte[] Timestamp GetSqlBinary Binary GetBytes
Tinyint Byte TinyInt GetSqlByte Byte GetByte
唯一識別碼 Guid UniqueIdentifier GetSqlGuid Guid GetGuid
varbinary Byte[] VarBinary GetSqlBinary Binary GetBytes
varchar 字串

Char[]
VarChar GetSqlString , GetString

GetChars
XML Xml Xml GetSqlXml Xml 無
JSON(JavaScript物件表示法) 字串 Json GetSqlJson 無 無
向量 無 Vector GetSqlVector 無 無

1 您無法將 DbType 的 SqlParameter 屬性設定為 SqlDbType.Date。
2 如果您知道 sql_variant 的基礎型別,請使用特定型別的存取子。

SQL Server 文件集

如需 SQL Server 資料類型的詳細資訊,請參閱資料類型 (Transact-SQL)。