I have a SQL Server 2014 server linked to an Oracle server. I want to use a temp table in a function to return a dataset from the Oracle database and then use the my function to return results using regular T-SQL. Since I am rather new to this I am close but am getting an error message
Msg 156, Level 15, State 1, Procedure GetBond, Line 37
Incorrect syntax near the keyword 'BEGIN'.
I have posted the function code here:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[GetBond]
(@WarControlID bigint)
RETURNS VARCHAR(MAX)
AS
BEGIN
--Create Temp Table
declare @TSQL varchar(max)
DECLARE @WarrantBail table
(
WR_INVL varchar(5),
WR_WARR_CTL VarChar(10),
WR_Bail VarChar(50),
WC_BAIL VarChar(50)
)
SELECT @TSQL = 'SELECT * FROM OPENQUERY(RMSPROD2,''SELECT TIBURON.WRMAST.WR_INVL, TIBURON.WRMAST.WR_WARR_CTL,TIBURON.WRMAST.WR_BAIL,TIBURON.WRWCHG.WC_BAIL
FROM TIBURON.WRMAST
LEFT JOIN TIBURON.WRWCHG ON WRWCHG.WC_WR_CHAIN = WRMAST.WRMAST_ROW
WHERE TIBURON.WRMAST.WR_WARR_CTL = ''''' + @WarControlID + ''''''')'
INSERT INTO @WarrantBail
EXEC (@TSQL)
END
BEGIN
-- Create a Variable
DECLARE @NoBailCount int
DECLARE @ChgCount int
DECLARE @WarTotalBond float
DECLARE @CHGTotalBond float
DECLARE @War_Final_Bail varchar(max)
Select COUNT(DISTINCT w.WR_Bail) AS NoBond_Count
From @WarrantBail w
Where w.WC_BAIL In ('No Bond', 'No Bail','None') Or w.WR_Bail In ('No Bond', 'No Bail','None')
--***********Get Charge Count
Select COUNT(w.WC_BAIL) As ChgCount FROM @WarrantBail w
--******************IF the above fails then we have a bond check the Warrant bond amount
Select SUM (DISTINCT cast(w.WR_Bail As int)) AS WAR_Bond_Total
From @WarrantBail w
Where w.WR_Bail Not In ('No Bond', 'No Bail','None')
--****************We may have additional charges get the total for those charges
Select SUM (cast(w.WC_BAIL As int)) AS CHG_BondTotal
From @WarrantBail w
Where w.WC_BAIL Not In ('No Bond', 'No Bail','None')
IF (@NoBailCount > 0)
Begin
SET @War_Final_Bail = 'NO BAIL'
End
ELSE IF @ChgCount > 0
Begin
SET @War_Final_Bail = @WarTotalBond + @CHGTotalBond
End
Else
Begin
SET @War_Final_Bail = @WarTotalBond
End
RETURN CONVERT(varchar(max), @War_Final_Bail)
END
In addition to the Error when I Execute the code I am also seeing a squiggly line under the Line "ALTER FUNCTION [dbo].[GetBond]
That error states:
Incorrect syntax: 'ALTER FUNCTION' must be the only statement in this batch.
Does this error mean I cannot create a temp table in the function?