gpt4 book ai didi

tsql - 嵌套的 SELECT 语句以我不理解的方式进行交互

转载 作者:行者123 更新时间:2023-12-01 06:39:12 25 4
gpt4 key购买 nike

我以为我明白如何做 SELECT来自另一个SELECT的结果声明,但似乎有某种我不明白的范围模糊。我正在使用 SQL Server 2008R2。

用一个例子来解释是最容易的。

创建一个带有单个 nvarchar 列的表 - 加载带有单个文本值和几个数字的表:

CREATE TABLE #temptable( a nvarchar(30) ); 
INSERT INTO #temptable( a )
VALUES('apple');
INSERT INTO #temptable( a )
VALUES(1);
INSERT INTO #temptable( a )
VALUES(2);

select * from #temptable;

这将返回: apple, 1, 2
使用 IsNumeric仅获取可以转换为数字的表行 - 这将保留文本值 apple在后面。这工作正常。
    select cast(a as int) as NumA
from #temptable
where IsNumeric(a) = 1 ;

这将返回: 1, 2
但是,如果我使用与内部选择完全相同的查询,并尝试执行数字 WHERE条款,它没有说不能转换 nvarchar值 'apple' 到数据类型 int .它是如何获得值(value)“苹果”的??
    select 
x.NumA
from
(
select cast(a as int) as NumA
from #temptable
where IsNumeric(a) = 1
) x
where x.NumA > 1
;

请注意,如果没有 WHERE,失败的查询也能正常工作。条款:
    select 
x.NumA
from
(
select cast(a as int) as NumA
from #temptable
where IsNumeric(a) = 1
) x
;

我觉得这非常令人惊讶。我没有得到什么? TIA

最佳答案

如果您查看估计的执行计划,您会发现它已将内部查询优化为外部查询并组合了 WHERE条款。

使用 CTE 来隔离操作工作(在 SQL Server 2008 R2 中):

declare @temptable as table ( a nvarchar(30) );  
INSERT INTO @temptable( a )
VALUES ('apple'), ('1'), ('2');

with Numbers as (
select cast(a as int) as NumA
from @temptable
where IsNumeric(a) = 1
)
select * from Numbers

关于tsql - 嵌套的 SELECT 语句以我不理解的方式进行交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12479244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com