Exec使用临时表 [英] Exec using Temporary table

查看:199
本文介绍了Exec使用临时表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

声明@tTable表(PeriodId int,Id int,Week varchar(50),res varchar(1000))

插入@tTable SELECT PeriodId,Id,Week ,res FROM mytable


声明@str varchar(max);
设置@ str ='select * from'+ @tTable
exec(@str)





执行时代码收到这样的错误



必须声明标量变量  @ tTable





我想显示@tTable中的所有内容。我怎样才能做到这一点 ?任何人都可以帮助我。

解决方案

在这种情况下,不要使用 EXEC ,只需 SELECT 声明:

  SELECT  * 
FROM @ tTable


使用#tTable代替@tTable

然后



 声明  @ str   varchar (max); 
set @ str = ' select * from #tTable'
exec @ str


首先在 exec(@set)的地方使用选择 @set 然后选择*来自@tTable返回多个列,所以我们可以在这里指定特定列...

还有一个更重要的事情是在一个批处理中执行所有语句因为表变量只存在于一个批处理中。

i我发表的声明..



  DECLARE   @ tTable   table (ID  INT ,UserName  VARCHAR  20 ),密码 VARCHAR  100 ),电子邮件 VARCHAR  30 ))

INSERT INTO @tTable SELECT * FROM 登录

DECLARE @ set VARCHAR (MAX)
SET @set =( SELECT [UserName] FROM @ tTable WHERE ID = ' 2'
SELECT @set


declare  @tTable table(PeriodId int, Id int,Week varchar(50) ,res varchar(1000))

insert into  @tTable SELECT  PeriodId,Id, Week, res   FROM  mytable


declare @str varchar(max);
set @str='select * from'+ @tTable
exec(@str)



while executing the code am getting an error like this

Must declare the scalar variable "@tTable".



I want to display all contents in @tTable . how can i do this ? Can Anyone help me.

解决方案

Do not use EXEC in this case, just SELECT statement:

SELECT *
FROM @tTable


use #tTable instead of @tTable
then

declare @str varchar(max);
set @str='select * from #tTable ' 
exec(@str)


first thing use select @set at the place of exec(@set) and select * from @tTable return more than one column so we can specify the particular column here...
And one more important thing execute the all statements in one batch because table variables have present only in a single batch.
i am giving the statements..

DECLARE @tTable table(ID INT,UserName VARCHAR(20),Password VARCHAR(100),Email VARCHAR(30))

INSERT INTO @tTable SELECT * FROM Login

DECLARE @set VARCHAR(MAX)
SET @set=(SELECT [UserName] FROM @tTable WHERE ID='2')
SELECT @set


这篇关于Exec使用临时表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆