Click here to Skip to main content
15,893,588 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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

SQL
Must declare the scalar variable "@tTable".


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

Do not use EXEC in this case, just SELECT statement:
SQL
SELECT *
FROM @tTable
 
Share this answer
 
Comments
Aswathi Narayan 23-Jul-14 5:32am    
Its a subquery inside my main query.. I can execute my main query using exec . So I want to display contents of the subquery using exec statement. Could u please help me?
Maciej Los 23-Jul-14 6:24am    
You need to understand that you create variable (type: table), not physical object. You can't use its name (name of variable) within EXEC statement.
Please, see the documentation[^].
use #tTable instead of @tTable
then

SQL
declare @str varchar(max);
set @str='select * from #tTable ' 
exec(@str)
 
Share this answer
 
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..

SQL
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
 
Share this answer
 
SQL
declare  @tTable table(PeriodId int, Id int,Week varchar(50) ,res varchar(1000))

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

select * from @tTable //Correct method to select data from @tTable 

In below code written by you is not in proper way because here @str is a variable not any object so you can't be able to access the data and stored whole query data because it's store only single value and "exec" it's a method to execute the stored procedure and worked for physical object

//Wrong way to select data from @tTable
declare @str varchar(max);
set @str='select * from'+ @tTable
exec(@str)



I hope you understand, what I'm trying to say.

Thank You......:-)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900