You can't execute dynamic sql or stored procedures inside a user-defined function. You can do this in a stored procedure and return the ID back through an output parameter:CREATE FUNCTION DBO.CrntPronID ( @VPREVPRONID BIGINT, @VEXTRACT BIGINT OUTPUT) ASBEGINDECLARE @VPREVBASE NVARCHAR(60)DECLARE @TEMPSQL NVARCHAR(4000)SET @VPREVBASE = (SELECT DBO.PREVBASE('OSDE'))/* if current base is 'OSDE2009_2' return 'OSDE2007_2' */EXEC('CREATE TABLE #CrntPronID (MULTI_ID BIGINT)')SET @TEMPSQL = 'SELECT ISNULL(MAX(PN.PRON_ID),0)FROM OSDPRON PNINNER JOIN OSDPOIK PKON PN.PRON_ID = PK.POIK_ID_PRONINNER JOIN OSDLINKBASESON PK.POIK_ID = LINKBASES_ID_POIKINNER JOIN [' + @VPREVBASE + '].DBO.OSDPRON OPNON LINKBASES_OLD_PRON_CODE = OPN.PRON_CODEINNER JOIN [' + @VPREVBASE + '].DBO.OSDPOIK OPKON LINKBASES_OLD_POIK_CODE = OPK.POIK_CODEAND OPN.PRON_ID = OPK.POIK_ID_PRONWHERE OPN.PRON_ID = ' + @VPREVPRONID + ' 'INSERT #CrntPronID (MULTI_ID) EXECUTE @TEMPSQLDECLARE @VEXTRACT BIGINTSET @VEXTRACT =( SELECT CAST(ISNULL(MAX(MULTI_ID),0) AS BIGINT)FROM TSP_CrntPronID )END
Usage: DECLARE @ID bigintEXEC DBO.CrntPronID @VPREVPRONID=10, @ID OUTPUTSELECT @ID