gpt4 book ai didi

sql - 在 SELECT 语句中使用 'previous' 列的结果

转载 作者:行者123 更新时间:2023-12-02 19:36:07 24 4
gpt4 key购买 nike

T-SQL 似乎允许我们从左到右在另一列的表达式中使用一列的值。例如:

declare @a int, @b int;
select @a = 2, @b = @a * 3;
select @a, @b;

产量 {2, 6}。

我在 BOL 等中找不到任何对此“功能”的引用。我的问题是,这是已知的、可靠的行为吗?

最佳答案

这实际上在 Variables (Transact-SQL) 中作为警告进行了介绍。 :

Warning

If there are multiple assignment clauses in a single SELECT statement, SQL Server does not guarantee the order of evaluation of the expressions. Note that effects are only visible if there are references among the assignments.

(强调我的)

SQL Server 一次为一个变量分配值,因此在这个(简单)示例中,SQL Server 已分配值 @a在评估(和分配)表达式 @a * 3 之前至@b .

正如警告所述,不要期望行为始终相同。如果您需要保证分配按严格的顺序进行,请将分配作为单独的语句进行:

DECLARE @a int,
@b int;
SET @a = 2;
SET @b = @a * 3;
SELECT @a, @b;

编辑:当使用非赋值表达式时,此行为存在。例如,以下语句将失败并出现错误“无效的列名'a'。”:

SELECT 2 AS a,
a * 3 AS b;

您所描述的行为仅发生在赋值语句中。您不能通过同一个 SELECT 中的别名来引用列它被定义了。

关于sql - 在 SELECT 语句中使用 'previous' 列的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57159772/

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