sql-server - SQL Server CTE隐式列数据类型问题

标签 sql-server common-table-expression

我在使用 SQL Server 公用表表达式 (CTE) 时遇到了一个非常奇怪的错误。

我认为通过给出代码示例来解释我的问题是最简单的。

CREATE TABLE #Test1 (TestCol varchar(3));

INSERT INTO #Test1 VALUES ('012')
INSERT INTO #Test1 VALUES ('ABC')

--This simple shows the Cast works as expected, and only on rows where the TestCol value is numeric
SELECT TestCol, CAST(TestCol as int) as IntCast 
FROM #Test1 
WHERE ISNUMERIC(TestCol) = 1;

--Here I create a cte using the same SQL as show above.
with cte as (
    SELECT 
       TestCol, CAST(TestCol as int) as IntCast 
    FROM #Test1 
    WHERE ISNUMERIC(TestCol) = 1
)

/*
I have two examples below. The first can be executed to check for the existence of our 'ABC' value.  It doesn't show up, which is expected. 
The Second example, simple checks to see if our IntCast column is greater than 10.  This throws an exception
*/

--SELECT * FROM cte
SELECT * FROM cte WHERE IntCast > 10

DROP TABLE #Test1

这里的异常(exception)是

Conversion failed when converting the varchar value 'ABC' to data type int

我很好奇这是在哪里发生的?

最佳答案

with cte as (
    SELECT TestCol, Case when ISNUMERIC(TestCol) = 1 then CAST(TestCol as int) else NULL end as IntCast FROM #Test1  
)

关于sql-server - SQL Server CTE隐式列数据类型问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13457130/

相关文章:

sql - 添加两个数据库之间的外键关系

sql - 如何在 SQL Server 中选择父行和子行

sql - 如何包装以下 CTE,以便我可以将其输出与 INSERT INTO 语句一起使用?

postgresql - 如何对一组 PostgreSQL 查询进行基准测试?

sql - 手动更改postgresql中查询的执行计划?

sql - Postgresql 中此 CTE 的正确方法

sql - 无法在具有唯一索引的对象中插入重复的键行

sql-server - Inno Setup - 尝试安装 NetFx3 功能时出现 "An attempt was made to load a program with an incorrect format"

sql - 将确切的一行移到所有行的顶部,留下所有其他的 ASCENDING

c# - SQL 查询中的期初余额和期末余额中的期末结果不正确?