Click here to Skip to main content
15,888,325 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
hello dears
Suppose that we have many tables, with name like "table1" and "table2" and "table3"
i want make query with varible name, so that i can make query on all tables
SQL
CREATE PROCEDURE selectWithVaribleTableName
@x int -- [any number between 1 and 1000]
as
declare @tablename nvarchar(256)
set @tablename ='table' + convert(nvarchar(100),@x)
select * from @tablename
go

but i get error.
please help me
Posted

In stored procedures all table names should be known at "compile time" meaning you can't use variable names.

If you need dynamic queries then you should use exec() : http://www.mssqltips.com/sqlservertip/1160/execute-dynamic-sql-commands-in-sql-server/[^]

However there are security issues associated with this and is discouraged.
 
Share this answer
 
Comments
Maciej Los 26-May-15 5:09am    
5ed!
Mehdi Gholam 26-May-15 5:09am    
Cheers Maciej!
[no name] 26-May-15 6:34am    
super cheers...
SQL
CREATE PROCEDURE selectWithVaribleTableName(@TableName Varchar(50))
as
begin
DECLARE @Query as varchar(max)
SET @Query = 'Select * FROM ' + @TableName
EXEC (@Query)
end
 
Share this answer
 
Comments
ali64iust 26-May-15 7:04am    
thank you very much
it works

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