4

SQL Server Common Table Expression (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

ここでの例外は

varchar 値 'ABC' をデータ型 int に変換するときに変換に失敗しました

これがどこで起こっているのか気になりますか?

4

1 に答える 1

3
with cte as (
    SELECT TestCol, Case when ISNUMERIC(TestCol) = 1 then CAST(TestCol as int) else NULL end as IntCast FROM #Test1  
)
于 2012-11-19T16:04:26.287 に答える