Sql Server 数据类型
数据类型 decimal 和 numeric
Decimal 和 numeric 是同义词,可互换使用,格式 decimal[ (p[ ,s] )] 和 numeric[ (p[ ,s] )]
其中p是精度(即整数位数+小数位数),该精度必须是从 1 到最大精度 38 之间的值, 默认精度为 18。
s是小数位数(小数点右侧存储的十进制数字位数),数值必须介于 0 和 p 之间,默认的确定位数为 0。
示例 :
-- 定义一个变量小数位位数为4,整数位位数为6(10-4) declare @x decimal(10,4) -- 小数位第5(小数位数+1)位会四舍五入 select @x=123456.0001480 select @x -- 输出结果 123456.0001 select @x=12345.0001550 -- 小数位 select @x -- 输出结果 12345.0002 /* * 下面这个赋值报错 ‘将 numeric 转换为数据类型 numeric 时出现算术溢出错误。’ * 报错原因:由于整数位数最大为10-4,这里赋值了一个整数部分为7位的值 */ select @x=1234567.0001550
decimal 等价于 decimal(18,0) 其中18是精度(即整数部分),0是小数位数
示例:
declare @y decimal select @y=38.13764 select @y -- 输出 38 ,第0+1位四舍五入 select @y=38.63764 select @y -- 输出 39 ,第0+1位四舍五入 select @y=123456789012345678 select @y -- 输出 123456789012345678 select @y=1234567890123456789 select @y -- 输出 将 numeric 转换为数据类型 numeric 时出现算术溢出错误 ,原因:长度超过默认18
varchar和nvarchar
if(object_id(N'dbo.test','U') is not null) drop table dbo.test -- 字段 f1 最多可以存放4个数字或者英文字符,或者2个汉字 create table test(f1 varchar(4)) insert into test(f1)values('测试1') -- 报错 将截断字符串或二进制数据。 if(object_id(N'dbo.test','U') is not null) drop table dbo.test -- 字段 f1 最多可以存放4个数字或者英文字符,或者4个汉字 create table test(f1 nvarchar(4)) insert into test(f1)values('测试测试1') -- 报错 将截断字符串或二进制数据。
字符变量的使用注意事项
-- 定义字符变量,会根据(n)其中的n的值截取字符串 declare @x1 char(2) select @x1='abcd' select @x1 '@x1' -- 输出结果 ab declare @x2 nchar(2) select @x2='abcd' select @x2 '@x2' -- 输出结果 ab declare @y1 varchar(2) select @y1='测试测试' select @y1 '@y1' -- 输出结果 测 中文占两个字节 declare @y2 nvarchar(2) select @y2='测试测试' select @y2 '@y2' -- 输出结果 测试 -- var 表示变长, n表示处理unicode数据类型(所有的字符使用两个字节表示)
表字段定义为允许null的影响
-- 创建测试表 if OBJECT_ID('tempdb..#t1') is not null drop table tempdb.#t1 go create table #t1(Id int null) insert into #t1(Id) values(null),(1),(null);
运行下面的查询语句: