存储过程中的 SQL Server 变量范围
我想在 SQL Server 存储过程的 if/else 语句中声明一个变量。我知道这是相当不可能的,因为 SQL Server 不会对过程中的变量声明进行内存管理。有没有办法在 if/else 语句中定义一个变量的作用域,然后在另一个 if/else 语句中重新声明具有相同名称的变量?例如:
create procedure Foo
as
begin
if exists (x)
begin
declare @bob int
set bob = 1
end
else
begin
declare @bob int
set bob = 2
end
end
I would like to declare a variable within an if/else statement in a SQL Server stored procedure. I understand that this is fairly impossible because SQL Server doesn't do memory management with respect to declaration of variables within procedures. Is there a way to have a variable scoped in an if/else statement, then redeclare a variable with the same name in another if/else statement? For example:
create procedure Foo
as
begin
if exists (x)
begin
declare @bob int
set bob = 1
end
else
begin
declare @bob int
set bob = 2
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
来自在线图书:
然而。没有什么可以阻止你这样做:
From books online:
However. Nothing keeps you from doing this:
不,SQL 非常有趣/奇怪,就像
在语句之前声明变量
如果存在
代码块所以
现在,看看这些示例并尝试猜测会发生什么
这当然有效,但并不是每次都初始化
No, SQL is pretty funny/weird like that
Declare the variable before the
if exists
block of codeso
Now, take a look at these examples and try to guess what happens
This of course works, but it is not initialized every time
有什么原因你不能这样做:
is there some reason why you can't do :
您可以求助于使用动态 SQL:
You could resort to using dynamic SQL: