0

这是对我之前的问题的跟进,在 t-sql 中

SELECT SCOPE_IDENTITY()

返回一个 BIGINT,我做了以下让它返回一个 INT:

DECLARE @X INT

INSERT ...

SELECT @X = SCOPE_IDENTITY()

-- if i don't include the line below, it will return a BIGINT

SELECT @X

为什么它会返回 BIGINT 除非我最后执行 SELECT @X ?

ps原来是

SELECT @X = SCOPE_IDENTITY()

不返回任何东西,它只是设置@x

4

2 回答 2

2

The statement

  SELECT @X = SCOPE_IDENTITY()

is an assignment statement. As in most programming languages, an assignment statement is executed by first evaluating the right hand side. In this case the right hand side evaluates to a bigint. When the value of @X gets the resulting bigint, there is an implicit type conversion, because @X is a different type (int) than the value it's receiving.

SQL is a typed language, and the type of an expression (such as SCOPE_IDENTITY() here) depends on the expression, not on what happens to the expression's value after evaluation.

Analogy:

DECLARE @i INT;
SET @i = 3.2 + 0.2;

You wouldn't suggest that 3.2 + 0.2 is an integer, would you? It's 3.4, a decimal. Only because of the assignment is there an implicit conversion to INT.

There's no magic in most programming languages.

于 2009-10-18T00:08:05.143 回答
1
SELECT SCOPE_IDENTITY()

如您所见,返回 BIGINT

SELECT @X = SCOPE_IDENTITY()

返回 BIGINT 并将其转换为 INT 变量 @X

因此,您将返回 BIGINT SCOPE_IDENTITY 并同时将其转换为 INT 并将结果设置为 @X。

返回 @X 返回 INT 结果。

只是关于这个主题的一些有趣的阅读。

SQL Server 7.0 联机丛书还声明:“建议使用 SET @local_variable 进行变量赋值,而不是 SELECT @local_variable。”

于 2009-10-17T19:09:46.743 回答