SQL语句表变量声明超出上下文

来源:百度知道 编辑:UC知道 时间:2024/07/07 14:44:40
declare @temp_table table(theDateTime char(6))
begin
begin
insert into @temp_table values ('asdqwe')
end
select @temp_table
end
执行的时候提示
Msg 137, Level 16, State 1, Line 7
Must declare the scalar variable "@temp_table".
为什么这样就超出了上下文了?

问题在这里select @temp_table是表变量,如果要查询结果要写成select * from @temp_table,select @temp_table系统会以为@temp_table是变量而不当表看,sql server 赋值语句是用set 或者select
declare @temp_table table( theDateTime char(6))
begin
begin
insert into @temp_table values ('asdqwe')
end
select * from @temp_table
end

这个是变量定义的问题吧。
给你个例子:
Declare @TableVar Table
(Cola int Primary Key,Colb char(3))

Insert Into @TableVar Values (1, 'abc')
Insert Into @TableVar Values (2, 'def')

Select * From @TableVar