代码之家  ›  专栏  ›  技术社区  ›  Limey

如何在视图中投射字符串

  •  0
  • Limey  · 技术社区  · 7 年前

    我有一个简单的视图,它接受varchar并将其转换为float。

    Select CAST(TRIM(Measurement) AS float) as Measurement
    from MyTable
    where Type = 'Some Value'
    

    现在视图将该列视为一个浮点,但是,当我尝试使用where clasue of MEASURATION=10查询我的视图时,我得到了错误:

    Error converting data type varchar to float.
    

    我知道字符串值总是一个数字(我已经检查了很多次)。在prod中出现此错误之前,我还通过多轮测试获得了此结果。我猜表中的其他测量值不是我的结果的一部分,而是导致此错误的原因(这些测量值在测试期间可能不存在)。

    有没有办法清理查询,使结果始终被视为浮点?

    谢谢

    1 回复  |  直到 7 年前
        1
  •  1
  •   Gordon Linoff    7 年前

    很明显,列中的值不正确。您可以使用正则表达式(在大多数数据库中)或 try_ SQL Server中的函数。

    例如:

    Select Measurement
    from MyTable
    where Type = 'Some Value' AND try_convert(float, measurement) is null;
    

    或:

    where type = 'Some Value' and
          not measurement ~ '^-?[0-9]*[.]?[0-9]+$'
    

    ~ 是正则表达式匹配的Postgres。其他数据库具有类似的功能,但语法不同。