November 2, 2010 at 4:01 am
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.
November 2, 2010 at 4:41 am
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
November 2, 2010 at 4:53 am
In addition to the key points raised by Gianluca, consider also the performance implications of putting this into a WHERE clause.
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
November 2, 2010 at 5:05 am
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