繁体   English   中英

设置局部变量并在整个查询批处理中使用?

[英]Set a local variable and use throughout the query batch?

在表中插入默认值后,我将范围标识的结果存储在变量中

insert into OrderPlaced default values;
declare @id bigint;
set @id = SCOPE_IDENTITY();

在此之后,我必须运行一些其他代码段来更改范围标识的值,并且在运行这些代码段之后,我必须再次使用 @id 的值,但它显示一个错误,指出我必须声明我的变量上面已经做了。

EXEC dbo.GetRecieptById @ID = @id;

不幸的是,我不能只选择整个代码块并立即执行它,因为这是用于演示的,我必须显示每个单独的步骤。

你想干什么 ?

如果要访问订单表中的最新数据,可以使用此代码访问最新数据。

SELECT MAX(ID) FROM OrderPlaced

局部变量不能在单独的执行中使用。 您必须将所有值存储在临时表中

这些表存储在tempdb 在表名开头使用带有一个#的本地临时表或带有两个##的全局临时表,如下所示:

create table #local_temp_table
(Id bigint not null);

...

insert into #local_temp_table ...

...

select Id from #local_temp_table;

要么

create table ##global_temp_table
(Id bigint not null);

...

insert into ##global_temp_table ...

...

select Id from ##global_temp_table;

当它们超出范围时会自动删除,但是,您可以手动删除它们。

看看下面的链接:

SQL Server 中的临时表

您的要求是如何跨批次保留变量 - 而不是在批次内。

一种方法是使用SESSION_CONTEXT

declare @id bigint;
insert into OrderPlaced default values;
set @id = SCOPE_IDENTITY();
EXEC sys.sp_set_session_context  @key= N'@id',@value = @id 

GO

declare @id bigint = CAST(SESSION_CONTEXT(N'@id') AS BIGINT)
EXEC dbo.GetRecieptById @ID = @id;

暂无
暂无

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

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