SQL Server 資料類型對應映射

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 GetDateTimeOffset
十進位 十進制 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
錢 十進制 Money GetSqlMoney Decimal GetDecimal
NCHAR 繩子

Char[]
NChar GetSqlString StringFixedLength GetString

GetChars
ntext 繩子

Char[]
NText GetSqlString String GetString

GetChars
數值 十進制 Decimal GetSqlDecimal Decimal GetDecimal
NVARCHAR 繩子

Char[]
NVarChar GetSqlString String GetString

GetChars
真實 單身 Real GetSqlSingle Single GetFloat
行版本 Byte[] Timestamp GetSqlBinary Binary GetBytes
smalldatetime 日期時間 DateTime GetSqlDateTime DateTime GetDateTime
SMALLINT Int16 SmallInt GetSqlInt16 Int16 GetInt16
smallmoney 十進制 SmallMoney GetSqlMoney Decimal GetDecimal
sql_variant (SQL資料型別變體) 物件 2 Variant GetSqlValue 2 Object GetValue 2
收發簡訊 繩子

Char[]
Text GetSqlString String GetString

GetChars
時間

(SQL Server 2008 及以後版本)
TimeSpan Time 無 Time GetTimeSpan
時間戳記 Byte[] Timestamp GetSqlBinary Binary GetBytes
Tinyint 位元 TinyInt GetSqlByte Byte GetByte
唯一識別碼 Guid UniqueIdentifier GetSqlGuid Guid GetGuid
varbinary Byte[] VarBinary GetSqlBinary Binary GetBytes
瓦查爾 繩子

Char[]
VarChar GetSqlString AnsiString、String GetString

GetChars
Xml Xml Xml GetSqlXml Xml 無

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

SQL Server 文件集

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

另請參閱