Dynamic sql in functions

  • Below is the dynamic statement which i try to excecute and throws error.

    Can any one suggest me the alternate way to return the value.

    CREATE FUNCTION dbo.fnDatafilter(@P_DTMOId AS BIGINT ,

    @P_AccessibleDataFilters AS Varchar(4000) ,

    @P_ActivityType AS varchar(100) ,

    @DFTableName AS varchar(100) ,

    @DFColumnName AS varchar(100)

    )

    RETURNS CHAR ( 1 )

    AS

    BEGIN

    DECLARE @V_INCLUDE CHAR(1)

    SET @V_INCLUDE = '0'

    DECLARE @v_SQLSTRING nvarchar(max)

    SET @v_SQLSTRING = ''

    SET @v_SQLSTRING='IF NOT EXISTS ( SELECT ''1'' FROM '+ @DFTableName +'DataFilter WHERE '+@DFColumnName +'= @P_DTMOId AND ActivityType = @P_ActivityType AND Status = ''A'') '

    SET @v_SQLSTRING = @v_SQLSTRING + 'BEGIN '

    SET @v_SQLSTRING = @v_SQLSTRING + ' SELECT @V_INCLUDE = ''1'''

    SET @v_SQLSTRING = @v_SQLSTRING + ' END'

    SET @v_SQLSTRING = @v_SQLSTRING + ' ELSE'

    SET @v_SQLSTRING = @v_SQLSTRING + ' BEGIN'

    SET @v_SQLSTRING = @v_SQLSTRING + ' IF EXISTS ( SELECT ''1'' FROM '+ @DFTableName +'DataFilter WHERE '+@DFColumnName +' = @P_DTMOId AND ActivityType = @P_ActivityType AND Status = ''A'' '

    SET @v_SQLSTRING = @v_SQLSTRING + ' AND DataFilterDefinitionOID IN ( SELECT OID FROM fGetBigIntList_221000 ( @P_AccessibleDataFilters ))) '

    SET @v_SQLSTRING = @v_SQLSTRING + ' BEGIN'

    SET @v_SQLSTRING = @v_SQLSTRING + ' SELECT @V_INCLUDE = ''1'' '

    SET @v_SQLSTRING = @v_SQLSTRING + ' END '

    SET @v_SQLSTRING = @v_SQLSTRING + 'END '

    --print @v_SQLSTRING

    EXEC @v_SQLSTRING

    RETURN ( @V_INCLUDE )

    END

    The output of this function is used in where condition of another procedure.

  • I'm afraid this can't be done. UDF cannot execute dynamic SQL.

    Some possible alternatives:

    a) Code it as a stored procedure

    b) Use IF statements to code a distinct SQL for each table (ugly)

    c) Code it as CLR function

    As a side note, scalar UDFs perform really bad. Consider using ITVFs instead.

    Hope this helps

    Gianluca

    -- Gianluca Sartori

  • In addition to the key points raised by Gianluca, consider also the performance implications of putting this into a WHERE clause.

    “Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw

    For fast, accurate and documented assistance in answering your questions, please read this article.
    Understanding and using APPLY, (I) and (II) Paul White
    Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden

  • Can you please post the error.....

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply