首页 > 解决方案 > 执行 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

标签: sqlsql-servertsql

解决方案


两个结果都是一样的,因为在转换后两个值都被转换为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 及以上版本中用于您的类型转换。


推荐阅读