Sunday, March 11, 2012

Declaring a tablename in a sproc as a parameter

Hi

Can someone please shed some light as to how this can be done.

With the below sql statement as you can see I don't want to declare the table name but would rather the table name be passed in via a parameter. I've tried declaring it as a varchar parameter but it doesnt seem to like it if I don't add a valid table name. Any ideas how this can be done. Thanks.

select * from @.tableName where condition = condition

exec ('select * from ' + @.tablename)

|||

Tried doing it with the statement and it doesnt work. Obviously you have to declare variable and set it, here's how I've done it below:


declare @.tablename varchar;
set @.tablename = 'tablename'
exec('select * from' + @.tablename)

I get an error saying invalid object name 't'

|||

try

declare @.tablename varchar (100)

|||

Yes, varchar == varchar(1).

Also you are missing a space after the FROM keyword: exec('select * from' + @.tablename), but, given the error message, this might just be the sample you have posted...

-LV

|||

I've got it working guys, thanks final code is:

declare @.tablename varchar(100);
set @.tablename = 'tbl_name'
exec('select * from ' + @.tablename)

No comments:

Post a Comment