【问题标题】:SQL Different column type comparison errorSQL 不同的列类型比较错误
【发布时间】:2012-10-01 13:57:44
【问题描述】:
您好,我有一个存储过程,假设在不同表的 2 列之间进行比较
- Users.ID => 整数
- Trans.ID => nvarchar
有时Trans.ID中的值根本不是数字,有时为null,这会导致尝试比较时出错
有没有办法尝试将 Trans.ID 解析为一个数字,以防万一它不成功返回 0??
我试过NullIf(),但是当里面的值不是数字时它不起作用。
【问题讨论】:
标签:
sql
sql-server
string
comparison
【解决方案1】:
假设Trans.ID是varchar(20)字段,可以将Users.ID字段转换为varchar,使用COALESCE处理NULL值,比较如下:
WHERE CAST(Users.ID AS varchar(20)) = COALESCE(Trans.ID, '')
【解决方案2】:
如果使用 sql server 你可以这样做
CASE WHEN ISNUMERIC(Trans.ID) = 0 then null
else cast(Trans.ID as int) end = Users.ID
【解决方案3】:
你可以这样做:
select * from users u
inner join trans t on u.userid = (CASE WHEN ISNUMERIC(t.id) = 1 THEN CONVERT(int, t.id) ELSE 0 END)
希望这会有所帮助。
【解决方案4】:
如果只是相等比较(我认为这是有道理的),我会将Users.ID 转换为NVARCHAR,然后与Trans.ID 进行比较。
【解决方案5】:
IsNumeric() 并不总是正确的,例如' - ' 和 '。'两者都为 IsNumeric 返回 1,但会使您的查询失败。
这个函数(改编自here)
create function dbo.GetNumeric(@x varchar(10)) returns float as
begin
return
case
when @x is null or @x = '' then null -- blanks
when @x like '%[^0-9e.+-]%' then null -- non valid char found
when @x like 'e%' or @x like '%e%[e.]%' then null -- e cannot be first, and cannot be followed by e/.
when @x like '%e%_%[+-]%' then null -- nothing must come between e and +/-
when @x='.' or @x like '%.%.%' then null -- no more than one decimal, and not the decimal alone
when @x like '%[^e][+-]%' then null -- no more than one of either +/-, and it must be at the start
when @x like '%[+-]%[+-]%' and not @x like '%[+-]%e[+-]%' then null
else convert(float,@x)
end
end
您的查询(涉及不等式)
where users.id >= case when IsNull(dbo.GetNumeric(trans.id),0)
如果trans.id不涉及小数点
where user.id >= case when trans.id not like '%[^0-9]%' and trans.id >''
then trans.id end
当然,如果是简单的相等,只需将 int 转换为 varchar
where right(users.id,10) = trans.id