I am attempting to create a Multi-Line Function in SQL Server that accepts a dynamic WHERE clause as a parameter. I need this so that the function can be as versatile as possible for the filter that needs to be applied. I am unfortunately getting an error upon creation of the function. I don't know how to solve the problem. Can someone advise me?
SQL:
SET
ANSI_NULLSON
GO
SET
QUOTED_IDENTIFIERON
GO
-- =============================================
-- Author:
-- Create date: 2/3/2014
-- Description: This multiline function will accept a generic WHERE Clause and apply it to the query for return.
-- =============================================
CREATE
FUNCTIONTESTMULTILINEFUNCTION
(
@WHEREvarchar(1024)
,@CHANGEDDATEasdatetime
)
RETURNS
@TESTTABLE
TABLE
(
IDint
,REVint
)
AS
BEGIN
Declare@SQLSTRINGvarchar(4096)
SET@SQLSTRING=''
SET@SQLSTRING=@SQLSTRING+'SELECT REVS.ID, REVS.Revision
FROM
(
Select distinct result.ID, Max(Rev) as ''''Revision''''
FROM
(
Select * from dbo.BugsAll
where
[Changed Date] < @CHANGEDDATE
) result
GROUP BY result.ID
) REVS
join dbo.BugsAll BA on (BA.ID=REVS.ID AND BA.REV=REVS.revision)'
IF(@WHEREisnotnullOR@WHERE<>'')
BEGIN
SET@SQLSTRING=@SQLSTRING+' WHERE '+@WHERE;
END
INSERT@TESTTABLE
EXEC(@SQLSTRING)
RETURN
END
GO
ERROR:
Msg 443, Level 16, State 14, Procedure TESTMULTILINEFUNCTION, Line 44
Invalid use of a side-effecting operator 'INSERT EXEC' within a function.
Senior Test Lead -- Microsoft