Click here to Skip to main content
15,879,326 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi all,

I have a query something like it.
SQL
DECLARE @execquery AS NVARCHAR(MAX)
SET @execquery =N'
declare @i varchar(50)
set @i=''139''

select * from ASYNCSEARCH_+@i'

Exec (@execquery)




this is not executing when I am running this query. I want to attach a string in table name.

I want the variable of @i to be defined just like I have done.I don't need it outside
Please help
Posted
Updated 5-Dec-13 0:02am
v2

Well, no - it won't...
Look at what you wrote:
SET @execquery =N'
declare @i varchar(50)
set @i=''139''

select * from ASYNCSEARCH_'+@i
SQL

It's a single string, containing the declaration of the variable, then trying to tack the variable on the end of the string it's declared in...
Did you mean:
SQL
declare @i varchar(50)
set @i='139'
SET @execquery =N'select * from ASYNCSEARCH_' + @i
 
Share this answer
 
Comments
Mohd Wasif 5-Dec-13 6:11am    
I have updated my question .I am in a condition of creating dynamic query for that on the basis of variable @i there exists a table like if value of @i=123 then table name becomes
ASYNCSEARCH_123.I have to get all records from that table.Can You help me.
OriginalGriff 5-Dec-13 6:30am    
Try it the way I suggested - you may find it works...
What is the purpose to declare the @i inside ?
can you try this below,
SQL
DECLARE @execquery AS NVARCHAR(MAX) 
declare @i varchar(50)
set @i='139'
SET @execquery =N'
 
select * from ASYNCSEARCH_'+@i
 
Exec (@execquery)
 
Share this answer
 
Comments
Mohd Wasif 5-Dec-13 6:16am    
Actually I am creating dynamic query that why there is need of declaring variable like that.

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