需要一些 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
This is a follow up to my previous question, in t-sql
SELECT SCOPE_IDENTITY()
returns a BIGINT, I did the following to get it to return an INT:
DECLARE @X INT
INSERT ...
SELECT @X = SCOPE_IDENTITY()
-- if i don't include the line below, it will return a BIGINT
SELECT @X
Why does it return a BIGINT unless I do SELECT @X at the end?
p.s. turns out
SELECT @X = SCOPE_IDENTITY()
doesn't return anything, it just sets @x
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该语句
是一个赋值语句。与大多数编程语言一样,赋值语句是通过首先评估右侧来执行的。在这种情况下,右侧的计算结果为 bigint。当 @X 的值获取结果 bigint 时,会发生隐式类型转换,因为 @X 的类型 (int) 与其接收的值不同。
SQL 是一种类型化语言,表达式的类型(例如此处的 SCOPE_IDENTITY())取决于表达式,而不取决于计算后表达式的值发生的情况。
类比:
你不会说 3.2 + 0.2 是一个整数,对吗?是 3.4,一位小数。仅因为赋值,才会隐式转换为 INT。
大多数编程语言都没有魔法。
The statement
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:
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.
返回 BIGINT 正如您所看到的,
返回 BIGINT 并将其转换为 INT 变量 @X
因此,您将返回 BIGINT SCOPE_IDENTITY,同时将其转换为 INT 并将结果设置为 @X。
返回 @X 返回 INT 结果。
只是关于该主题的一些有趣的阅读。
returns a BIGINT as you have seen
returns BIGINT and casts it into INT variable @X
So you are returning BIGINT SCOPE_IDENTITY and also concurrently casting it to INT and setting that result to @X.
Returning @X returns the INT result.
Just some interesting reading on the subject.