Is it possible to pass in the name of a table into a stored procedure?
For example, suppose you have several views of the same table. They all have the exact same structure.
You want a stored procedure that can be run for any of the views.
Something like:
create procedure myprocedure
@tableName varchar(50) = ''
select blah from @tableName where blah = blah2
When I try to do this, I get
Must declare the table variable @tablename
Any ideas how I can do this?
Best Answer
Instead of creating views, why not make an inline table-valued function - effectively a parameterized view. You basically get all the benefits of views AND parameters.
Another thing you can do in your TVF is something like this:
Now your ranges have names (in a table where they can be easily managed without changing the schema) - this also fairly seamlessly handles multiple ranges with the same name, although if ranges overlap you can have duplicates due to the join matching both.
Also, please consider avoiding BETWEEN:
I strongly suggest that you reconsider your requirements and when asking questions here be sure to include more about your motivations, because when you bring in a question with a preconceived notion of what the solution is, you are likely to get a suboptimal solution. (like the dynamic SQL solutions given aren't going to easily work for your OR case, but that information about the problem space is buried in a comment from you)
From: http://sqlfiddle.com/#!6/a628a/1
This part:
Means that each log item will be joined to the ranges it fits in (by date), each range will join to the groups they are in, but only that group selected will be used.