I need some help. I am working with a SQL function that generates a dynamic query and apparently everything is correct, it does not throw any error, the problem is that when I call the function the result I get is the complete query and I need the result of the query. I don't know how to proceed because I can't use instructions like EXEC sp_executesql @sql
inside a function.
Any advice?
Here's my function
CREATE FUNCTION [dbo].[GetAmount](
@Table NVARCHAR(30),
@Column NVARCHAR(30),
@Id NVARCHAR(30)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
RETURN ('SELECT ' + @Column + ' FROM ' + @Table + ' WHERE ID = ' + @Id)
END
call to function
dbo.GetAmount('Sales','Amount','123')
this is the result I got
SELECT Amount FROM Sales WHERE ID = 123
result I want (amount of sales)
$230
I know that there are simpler ways to do this but due to the structure of the database it is necessary to apply this solution, also the same function will be used to retrieve values from different tables.