How can I provide the FROM clause of a SELECT statement from a UDF parameter
In the web porting application I am currently working on, we are currently dynamically accessing various tables at runtime from startup to startup based on a specified "wildcard" string. I would like to shift this burden to get back to the database now that we are moving to SQL Server, so I don't need to mess with the dynamic GridView. I was thinking about writing a table-valued UDF with a parameter for the table name and one for the WHERE clause.
I entered the following for my UDF, but obviously it doesn't work. Is there a way to take a varchar or string of some type and get a table reference that can work in a FROM clause?
CREATE FUNCTION TemplateSelector
(
@template varchar(40),
@code varchar(80)
)
RETURNS TABLE
AS
RETURN
(
SELECT * FROM @template WHERE ProductionCode = @code
)
Or some other way to get a result set similar to this concept. Basically all records in the table are specified with varchar @template with corresponding production @code.
I am getting the error "Must declare table variable '@template'", so the SQL server is probably all I am trying to fetch from the table.
In the editor: Yes, I don't need to do this in a function, I can run stored proxies, I haven't written them yet.
source to share
I have a finite number of tables that I want to be able to address, so I could write something using IF that @template tests for matches to a range of values ββand for each match is done
SELECT * FROM TEMPLATENAME WHERE ProductionCode = @code
It looks like this is the best option
source to share