Dynamic SQL is dangerous. You never want to substitute passed values directly into an sql string. Fortunately, it sounds like you already know that.
Unfortunately, in this case you've discovered the problem that you can't use an sql parameter for the table name. So, what to do? You don't want to use the passed value in dynamically generated sql but you can't put it in a query in the normal safe way.
The answer is a lookup table. Create a 'tables' table that holds the name of each of your specific tables. It should look kind of like this:
CREATE TABLE [tables] (table_name sysname)
Then you can write a query that looks something like this:
SELECT @tblSpecific = table_name FROM [tables] WHERE table_name = @tblSpecific
Now you just have to check whether @tblSpecific
is NULL
. If it's not, then it's safe to use in a dynamic sql statement (and dynamic sql is ultimately your only option here: even the user defined function has you doing that at some level).
Oh, and one more thing-- my choice of names and types for the lookup table is not an accident. The SQL Standard already has a table like this (well, a view anyway). Just use INFORMATION_SCHEMA.Tables
.