简体   繁体   English

从 select 语句分配变量

[英]Assigning variable from select statement

Which is the correct syntax?哪个是正确的语法?

DECLARE @TotalRows INT
SET @TotalRows = (SELECT COUNT(*) FROM MyTable WHERE MyID = Value)

OR或者

DECLARE @TotalRows INT
SELECT @TotalRows = COUNT(*) FROM MyTable WHERE MyID = Value

Does it even matter?这还重要吗?

Difference between set vs select设置与 select 之间的区别

  1. SET is the ANSI standard for variable assignment, SELECT is not. SET 是变量赋值的 ANSI 标准,SELECT 不是。
  2. SET can only assign one variable at a time, SELECT can make multiple assignments at once. SET 一次只能赋值一个变量,SELECT 一次可以进行多个赋值。
  3. If assigning from a query, SET can only assign a scalar value.如果从查询分配,SET 只能分配一个标量值。 If the query returns multiple values/rows then SET will raise an error.如果查询返回多个值/行,则 SET 将引发错误。 SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one) SELECT 会将其中一个值分配给变量并隐藏返回多个值的事实(因此您可能永远不知道为什么其他地方出了问题 - 乐于排除故障)
  4. When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from its previous value)当从查询分配时,如果没有返回值,则 SET 将分配 NULL,其中 SELECT 根本不会进行分配(因此变量不会从其先前的值更改)
  5. As far as speed differences - there are no direct differences between SET and SELECT.至于速度差异 - SET 和 SELECT 之间没有直接差异。 However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.然而,SELECT 一次完成多项任务的能力确实使其在速度上比 SET 稍有优势。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM