1

I've done a lot of functions that return a table but somehow this one keeps on giving me an error at Begin and I couldn't figure out for the life of me why. My where statement is stored in a table. This function I want to pass in a value and the where statement.

CREATE FUNCTION dbo.Testtesttest(@employeeID        AS INT,
                                 @sqlWhereStatement AS VARCHAR(max))
Returns TABLE
  BEGIN
      DECLARE @mySQLStatement VARCHAR(max)

      SET @mySQLStatement = 'Set Quoted_Identifier OFF Select '
                           + CONVERT(VARCHAR, @employeeID) + ',* from (
        select m.ManagerID, m.Name,m.Email,e.BU,
        e.PSC from m inner join e on m.ManagerID = e.EmployeeID
        group by m.ManagerID, m.Name,m.Email,e.BU,e.SC,
        e.PSC) x where ' + @sqlWhereStatement

      EXEC(@mySQLStatement)

      RETURN
  END 

2 Answers 2

3

You can't use dynamic SQL in a function so what you are trying to do is not possible via a TSQL TVF.

Maybe a CLR UDF can do something like this but I would find a different approach anyway.

Sign up to request clarification or add additional context in comments.

2 Comments

if have i have function returning a complete sql string, can I do this exec(myFunctionThatReturnSQLString) but sadly this won't work as well. :( any thoughts?
@chungtinhlakho - You haven't really explained your root problem. Just your proposed solution, which isn't possible, but probably something here will help.
0

Why don't you just wrap that logic in a stored procedure? If you need to take the results of sproc into a table, you can use INSERT INTO EXEC

INSERT INTO
yourTable(col1, col2, col3)
EXEC Testtesttest @employeeID, @sqlWhereStatement 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.