sql - 执行 max() 时 varchar 和 int 的区别?
问题描述
当 table.column 是 varchar 或 int 时,这两者之间是否存在技术差异?什么时候结果不一样?我尝试了几个数字值的示例(例如 1、'1' 等),结果是相同的。
-- table.column is int:
select
MAX(table.column) as m
-- table.column is varchar:
select
MAX(CAST(table.column as int)) as m
解决方案
两个结果都是一样的,因为在转换后两个值都被转换为int
类型。
如果任何实际int
类型转换为的字符串int
在那里没有任何区别。但是,如果您有任何其他类型的字符串,并且将该字符串转换为int
类型,则会出现错误。
declare @str nvarchar(100)
set @str = 'sdsfd fdf fd dfsf'
select cast(@str as int)
消息 245,级别 16,状态 1,行 3486 将 nvarchar 值“sdsfd fdf fd dfsf”转换为数据类型 int 时转换失败。
对于可以转换为整数的字符串,聚合函数没有区别。
declare @dd table ( id varchar(max), id2 int)
insert into @dd ( id, id2 )
values ( '1', 1 )
, ( '99', 99 )
, ( '52', 52 )
select max(id2) as col, max(cast(id as int)) as col1 from @dd
Result
------------------
col col1
99 99
感谢@Zohar 提醒。
虽然最好Try_cast
在 SQL Server 2012 及以上版本中用于您的类型转换。
推荐阅读
- php - 需要获取任务标签在 $TagArray 中的任务
- python - 将 Python 数组中的值 0.00 替换为文本字符
- excel - 如何在Excel中输入句点
- angular - 等待可观察完成 - Angular
- .net - 程序等待 API 调用完成
- c++ - C++ 从它自己的类中删除一个对象
- wpf - 技术上是否可以将 wpf Xaml 元素渲染为 direct3d 纹理?
- html - XSLT 加倍输出与切换的 HTML 视图的差异
- sql - 如何使用 TIMESTAMPDIFF 获取 PostgreSQL 中 2 个日期之间的差异?
- python - 为什么 python 在函数和表达式中对星号的处理方式不同?