简体   繁体   English

为什么此查询不起作用?

[英]Why this query doesn't work?

Why the query below doesn't work in SQL Server 2008? 为什么下面的查询在SQL Server 2008中不起作用?

SELECT 
    CONVERT(INT, TEMP.observ_value) AS value
FROM
    (SELECT observ_value 
     FROM LAB_RESULTS
     WHERE observ_value NOT LIKE '%[^0-9]%') TEMP  
WHERE 
    observ_value >= 190

Here, is the error: 这是错误:

Msg 245, Level 16, State 1, Line 5 消息245,第16级,状态1,第5行
Conversion failed when converting the varchar value 'SCREEN' to data type int. 将varchar值“ SCREEN”转换为数据类型int时,转换失败。

The observ_value column is varchar . observ_value列是varchar However, I have already only chosen the int values in the subquery. 但是,我已经只选择了子查询中的int值。

Unfortunately, the SQL Server query optimiser can and will rearrange items from your query in ways that may cause errors to be introduced that weren't there in your original query. 不幸的是,SQL Server查询优化器可以并且将以可能导致引入原始查询中没有的错误的方式重新排列查询中的项目。 This is heavily dependent on the precise query plan that gets used, which in turn depends not only on the table definition and query text, but also on how your values are distributed. 这在很大程度上取决于所使用的精确查询计划,这不仅取决于表定义和查询文本,还取决于您的值如何分配。

In your case, it's possible that SQL Server will check observ_value >= 190 , implicitly converting observ_value to int , before checking that observ_value NOT LIKE '%[^0-9]%' . 在您的情况下,SQL Server可能会检查observ_value >= 190 ,将observ_value隐式转换为int ,然后再检查observ_value NOT LIKE '%[^0-9]%' Whether this is a valid re-ordering of your query is arguable, but even if it's not valid, it's something SQL Server does and something you have to work around. 这是否是对查询的有效重新排序是有争议的,但是即使它无效,这也是SQL Server要做的事情,您必须解决。

Re-write your query to make sure no conversion of non-numeric values to int can ever be performed: 重新编写查询,以确保无法将非数字值转换为int

SELECT 
    TEMP.observ_value AS value
FROM
    (SELECT CASE
         WHEN observ_value NOT LIKE '%[^0-9]%'
         THEN CONVERT(INT, observ_value) END
         AS observ_value
     FROM LAB_RESULTS
     WHERE observ_value NOT LIKE '%[^0-9]%') TEMP  
WHERE 
    observ_value >= 190

You can use ISNUMERIC function 您可以使用ISNUMERIC函数

SELECT CONVERT(INT, observ_value) AS value
    FROM LAB_RESULTS
    WHERE  ISNUMERIC(observ_value)= 1 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM