Click here to Skip to main content
15,907,687 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I want to make a function in sql server 2008 which accepts table name as a parameter.
Eg:

SQL
create function test(@tbl varchar(50))
returns @m float
begin
select @m=id from @tbl
return
end

But this
is not accepting table name as a variable.
Posted

Instead of function, use stored procedure:
SQL
create procedure test
    @tbl varchar(50)
AS
BEGIN
    DECLARE @sql VARCHAR(2000)
    SET @sql = N'select id from ' + @tbl

    EXEC(@sql)
END
 
Share this answer
 
Comments
Saksham_Agrawal 19-Aug-13 9:00am    
with proc it is achievable but I want the same with function only.
Maciej Los 19-Aug-13 9:16am    
The reason why you can't do it in function is here: http://stackoverflow.com/questions/9607935/call-dynamic-sql-from-function[^]
Saksham_Agrawal 19-Aug-13 9:21am    
DML is not allowed in Functions. But passing table name as a parameter doesnt change the structure of database.

http://www.itdeveloperzone.com/2012/12/passing-table-to-function-sql.html
 
Share this answer
 
v2
Comments
Saksham_Agrawal 19-Aug-13 9:12am    
thanks dude. But how to call that function now with table name as a parameter?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900