Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a variable for table name in 'From' clause in SQL Server 2008

I have a UDF that queries data out of a table. The table, however, needs to be definable as a parameter. For example I can't have:

Select * From [dbo].[TableA]

I need something like:

Select * From [dbo].[@TableName]

The above line doesn't work, and also the UDF prohibits me from setting the query as a string and calling exec(). I can do this in a procedure, but I can't call the procedure from the UDF either.

Does anyone know how I can accomplish this within the UDF without having some kind of massive switch statement?

like image 334
DaveK Avatar asked Jun 12 '09 19:06

DaveK


People also ask

Can a table name be a variable in SQL Server?

Table variable is a type of local variable that used to store data temporarily, similar to the temp table in SQL Server. Tempdb database is used to store table variables. To declare a table variable, start the DECLARE statement. The name of table variable must start with at(@) sign.

How do you assign a value from a table to a variable in SQL?

When a variable is first declared, its value is set to NULL. To assign a value to a variable, use the SET statement. This is the preferred method of assigning a value to a variable. A variable can also have a value assigned by being referenced in the select list of a SELECT statement.

Can I use variable in where clause SQL?

You can't use a variable in an IN clause - you need to use dynamic SQL, or use a function (TSQL or CLR) to convert the list of values into a table.


2 Answers

SET @SQL = 'SELECT * FROM ' + @table
EXEC (@SQL)  -- parentheses are required
like image 74
johnnycrash Avatar answered Oct 13 '22 00:10

johnnycrash


This can't be done, dynamic SQL is not supported in functions.

See this SO question: Executing dynamic SQL in a SQLServer 2005 function

like image 33
Andomar Avatar answered Oct 12 '22 23:10

Andomar