特殊的資料類型: bit、sql_variant、sysname

來源:互聯網
上載者:User

標籤:

在SQL Server中,特殊的資料類型主要有三個,分別是:bit、sql_variant 和 sysname

一,bit

bit類型,只有三個有效值:0,1 和 null,字串true或false能夠隱式轉換為bit類型,true轉換為1,false轉換為0;任何非0的整數值轉換成bit類型時,值都是1。

1,將字串 true 和 false 隱式轉換成 bit 類型

declare @bit_true bitdeclare @bit_false bitset @bit_true=‘true‘set @bit_false=‘false‘select @bit_true,@bit_false

2,儲存空間

bit類型儲存 0 和 1 ,只需要使用 1 bit 就能表示,但是,在儲存到Disk時,SQL Server按照Byte來分配儲存空間。如果表中只有1個 bit 列,那麼該列將會佔用1Byte的空間,一個Byte最多儲存8個bit列。

The SQL Server Database Engine optimizes storage of bit columns. If there are 8 or less bit columns in a table, the columns are stored as 1 byte. If there are from 9 up to 16 bit columns, the columns are stored as 2 bytes, and so on.

二,sql_variant

1,儲存空間

sql_variant 是變長的資料類型,包含兩部分資訊:基礎類型和Value,最多儲存8000Byte的資料。

sql_variant includes both the base type information and the base type value. The maximum length of the actual base type value is 8,000 bytes.

declare @sv sql_variantset @sv=REPLICATE(‘abcd‘,2001)--max bytes:8000select len(cast(@sv as varchar(max)))

2,賦值和運算

在賦值時,SQL Server 自動將其他資料類型隱式轉換為sql_variant類型,但是,SQL Server不支援將sql_variant類型隱式轉換成其他資料類型,必須顯式轉換。不能直接對sql_variant進行運算,例如,在對sql_variant 類型進行算術/字元操作時,必須顯式將其轉換成基礎資料類型,然後才能對其進行運算。

When handling the sql_variant data type, SQL Server supports implicit conversions of objects with other data types to the sql_variant type. However, SQL Server does not support implicit conversions from sql_variant data to an object with another data type.

declare @var_int sql_variantdeclare @var_bit sql_variantset @var_bit=‘true‘set @var_int=10select @var_bit,@var_int,cast(@var_bit as bit),cast(@var_int as int)

三,sysname

sysname 是一個系統資料類型,用於定義表列、變數以及預存程序的參數,是nvarchar(128) 的同義字,當該類型用於定義table column時,SQL Server 會自動添加 not null ,等價於nvarchar(128) not null。

查看sysname的定義

exec sp_help  sysname 

  • 使用sysname定義變數或參數時,等價於 nvarchar(128)
  • 使用sysname定義column的類型時,等價於 nvarchar(128) not null

當使用sysname定義column的類型時,SQL Server 自動在sysname 後面加上not null,即 sysname not null,等價於 nvarchar(128) not null

create table dbo.dt( 
  col sysname
)
--系統產生的create table 指令碼CREATE TABLE [dbo].[dt]( [col] [sysname] NOT NULL)

 

參考文檔:

sql_variant (Transact-SQL)

特殊的資料類型: bit、sql_variant、sysname

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.