从函数调用动态SQL

前端之家收集整理的这篇文章主要介绍了从函数调用动态SQL前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在编写一个返回表的函数.传递给函数的参数有两个参数,构建并执行查询并将其插入到返回表中.但是我收到这个错误.

Only functions and some extended stored procedures can be executed from within a function. @H_502_4@

我不想使用存储过程,因为这是一个简单的效用函数.有人知道这是否可以完成.我的功能编码如下,它检查某个表中某列的重复.@H_502_4@

-- =============================================
-- AUTHOR:      JON AIREY
-- THIS FUNCTION WILL RETURN A COUNT OF HOW MANY
-- TIMES A CERTAIN COLUMN VALUE APPEARS IN A 
-- TABLE. THIS IS HELPFUL FOR FINDING DUPES.

-- THIS FUNCTION WILL ACCEPT A COLUMN NAME,TABLE
-- NAME (MUST INCLUDE SCHEMA),AND OPTIONAL
-- DATABASE TO USE. RESULTS WILL BE RETURNED AS
-- A TABLE.
-- =============================================
ALTER FUNCTION [dbo].[fn_FindDupe]
(   
-- Add the parameters for the function here
@Column     VARCHAR(MAX),@Table      VARCHAR(100),@Database   VARCHAR(100)    =   ''
)
RETURNS 
@TempTable TABLE 
        ([Column] varchar(100),[Count] int)
AS
BEGIN
    DECLARE @sql VARCHAR(MAX)
    SET @Table =    CASE
                        WHEN @Database = ''
                        THEN @Table
                        ELSE @Database + '.' + @Table
                    END

    SET @sql =

    '   
        INSERT INTO @TempTable

        SELECT      ' + @Column + ',COUNT(' + @Column + ') AS CNT
        FROM        ' + @Table + '
        GROUP BY    ' + @Column + '
        ORDER BY    CNT DESC
    '

    EXEC SP_EXECUTEsql @sql

RETURN 
END
GO

解决方法

You can’t use dynamic sql in a udf

This very simple: you cannot use dynamic sql from used-defined
functions written in T-sql. This is because you are not permitted do
anything in a UDF that could change the database state (as the UDF may
be invoked as part of a query). Since you can do anything from dynamic
sql,including updates,it is obvIoUs why dynamic sql is not
permitted.@H_502_4@

…@H_502_4@

In sql 2005 and later,you could implement your function as a CLR function. Recall that all data access from the CLR is dynamic sql. (You are safe-guarded,so that if you perform an update operation from your function,you will get caught.) A word of warning though: data access from scalar UDFs can often give performance problems.@H_502_4@

猜你在找的MsSQL相关文章