Dynamic function call in SQL

Is it possible to call a function with a dynamic name in SQL?

For instance:

SELECT functionid, (SELECT results FROM dbo.Function_*functionid*) AS results FROM List_of_Functions 

This will call a different function for each row in the List_of_Functions table.

Or am I all wrong about this?

+3
source share
2 answers

You will need to build (either enter it, or create dynamically based on your table) an SQL query like:

 SELECT functionid ,CASE functionid WHEN 1 THEN dbo.Function_1() WHEN 2 THEN dbo.Function_2() WHEN 3 THEN dbo.Function_3() END AS results FROM List_of_Functions 

Instead of creating all these functions, would it not be better to create one function and pass the value that the function can use to differentiate processing? as:

 SELECT functionid ,dbo.Function(functionid) AS results FROM List_of_Functions_Parameters 
+3
source

Is it possible to call a function with a dynamic name in SQL?

Not in pure SQL.

You can achieve this using dynamic SQL, but not without any risk, in particular, SQL Injection .

I suggest reading The Curse and the Blessings of Dynamic SQL by Erland Sommarskog for a comprehensive study of the subject.

+2
source

Source: https://habr.com/ru/post/1415173/


All Articles