特殊的數據類型: bit、sql_variant、sysname


在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 bit
declare @bit_false bit
set @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_variant
set @sv=REPLICATE('abcd',2001)
--max bytes:8000
select 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_variant
declare @var_bit sql_variant

set @var_bit='true'
set @var_int=10

select @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)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM