Share via

SQL Server facing problem to compile function

Sudip Bhatt 2,281 Reputation points
2021-02-03T15:03:58.537+00:00

This is my function code which is not getting compile. error is not clear. please tell me what to change in code.
can't we return result set executing dynamic sql ?

thanks

CREATE FUNCTION Fn_GetDelTaData 
(  
    @Ticker VARCHAR(20)
)
RETURNS TABLE 
AS

 BEGIN
 DECLARE @Columns as VARCHAR(MAX),@SQL VARCHAR(MAX)
 SELECT @Columns =
 COALESCE(@Columns + ', ','') + QUOTENAME(Broker)
 FROM
    (SELECT DISTINCT Broker
 FROM tblOutputDetl_csmtuner where Ticker=@Ticker AND TRIM(Broker)<>''
    ) AS B
 ORDER BY B.Broker

 SET @SQL ='SELECT * FROM   
 (
 SELECT 
 Section, 
 LineItem,
 Broker,
 ItemValue_NoFormat
 FROM 
 tblOutputDetl_csmtuner where Ticker='''+@Ticker+'''
 ) t 
 PIVOT(
 Max(ItemValue_NoFormat) 
 FOR Broker IN ('+@Columns+')
 ) AS pivot_table'

 RETURN EXEC(@SQL)
 END
Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

0 comments No comments

Answer accepted by question author

Tom Phillips 17,786 Reputation points
2021-02-03T15:20:58.71+00:00

You cannot use dynamic sql or EXEC inside a function.
Please see:
https://blog.sqlauthority.com/2007/05/29/sql-server-user-defined-functions-udf-limitations/

Was this answer helpful?


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.