自定义函数执行动态sql语句

--函数中不能调用动态SQL,使用用存储过程吧。如果还要对函数做其他操作,换成存储过程不方便,可以考虑把其他操作一起封装在存储过程里面。如:
 
create proc [dbo].[FUN_YSCL_GetSpvalue]
@FormID VARCHAR(200)
AS
BEGIN
 
    DECLARE @TableID VARCHAR(20)
    SELECT @TableID = tb.vcTableID FROM tG10Money tm LEFT JOIN tG10Tables tb ON tm.iFormType = tb.ID WHERE vcFormID = @FormID
    DECLARE @strSQL NVARCHAR(2000)
    SET @strSQL = ''
    SET @strSQL += ' SELECT '
    SET @strSQL += '@spvalue=tb.SPValue'
    SET @strSQL += ' FROM ' + @TableID + ' tb'
    SET @strSQL += ' RIGHT JOIN ( SELECT DISTINCT'
    SET @strSQL += ' FormID ,'
    SET @strSQL += ' MAX(WFNodeIndex) AS maxnode'
    SET @strSQL += ' FROM tFS1001'
    SET @strSQL += ' WHERE RowType = 1'
    SET @strSQL += ' GROUP BY WFID ,'
    SET @strSQL += ' FormID'
    SET @strSQL += ' ) maxnode'
    SET @strSQL += ' ON tb.FormID = maxnode.FormID'
    SET @strSQL += ' AND tb.WFNodeIndex = maxnode.maxnode'
    SET @strSQL += ' WHERE tb.FormID= '''+@FormID+''''
     
    DECLARE @spvalue VARCHAR(20)
    EXEC sp_executesql @strSQL,N'@spvalue VARCHAR(20) out',@spvalue OUTPUT
     
    select FormID,@spvalue FROM tFormMoney
END
原文地址:https://www.cnblogs.com/zs6666/p/5975913.html