EDIT: Some of those who would offer help are unclear about the nature of the requirement, so I will try to state it as clearly as I can:
We need to instantiate a view of an underlying table, and this view must be able to be joined to another table; the difficulty is that the identity of the underlying table is not known until runtime of the ad hoc query doing the join. We would like to do something like this:
select * from foo
inner join dynamicallyInstantiatedTable(condition) DT
on foo.zipcode = DT.zipcode
It doesn't seem possible to create a function that returns TABLE if the function uses dynamic SQL. This is not valid:
declare @tablename varchar(50);
-- <snip> code to determine the name of @tablename
declare @statement varchar(1000);
set @statement = 'select * from ' + @tablename;
exec( @statement);
The error:
Invalid use of a side-effecting operator 'EXECUTE STRING' within a function.
If the table name is not known beforehand for whatever reason (e.g. tables are constantly being added and we must select against the most recent one, say), is it possible to do the select dynamically and return a table, either in a stored proc or function?
select * from myproc inner join T....SELECT * FROM OPENQUERY(YOURSERVERNAME, 'EXEC MyProc @parameters')combined with dynamic SQL may work, But still I wouldn't go that waytables are constantly being added and we must select against the most recent oneIt indicates table per date, which is IMHO poor design. And it is antipattern SELECT * FROM sales + @yymm