当表名作为参数传入时,如何从函数运行查询

时间:2012-03-16 18:51:58

标签: sql-server sql-server-2008

我正在编写一个将table-name作为参数的函数。 我知道表中需要的列名,但是表名+表所有者是动态传入的(我需要这样,但它目前无效)。

看起来像这样:

CREATE FUNCTION [myowner].  
[alex_diff](@fromdate datetime, @todate datetime, @table_name varchar(256), @country_code varchar(3))  
RETURNS int  
AS  
BEGIN
...
set @date_string = (select calendar_month2 from ??? where calendar_year=@current_year and country_code = @country_code)
...
END

我无法用@table_name代替'???' 这给了我错误:

  

Msg 1087,Level 16,State 1,Procedure alex_business_date_diff,Line   53必须声明表变量“@table_name”。

如何在动态传递的表名上执行SQL?

我尝试过以下操作:

    set @statement = 'select @output=' + @column_name + ' from ' + @table_name + ' where calendar_year=' + cast(@current_year as varchar(4)) + ' and country_code = ' + @country_code;
    EXEC sp_executesql @statement, N'@output varchar(31) OUTPUT', @date_string OUTPUT

但是得到这个错误(当我尝试运行该函数时):

  

消息557,级别16,状态2,行1仅功能和一些扩展   存储过程可以在函数内执行。

2 个答案:

答案 0 :(得分:1)

您可以在SQL Server中使用CLR并利用运行动态SQL的.NET语言。

答案 1 :(得分:1)

您可以使用所有动态操作创建存储过程,并通过输出参数使用结果。