I am attempting to dynamically build a T-SQL statement based on a FieldMapping table and some business rules.
Cut the long story short, I have a function that will return the SQL statement as a varchar(max) that I will execute as EXEC (@Sql)
in my stored procedure.
Allow me to demonstrate with a test table
create procedure [dbo].[sp_TestInsert]
(
@Id int,
@Name varchar(20),
@Surname varchar(20),
@Age int,
@Source varchar(1)
)
as
declare @sql varchar(max)
-- Return SQL statement that depends on business rules
-- i.e. if the @Source = 'i' the returned SQL will be:
-- "update TestTable set Name = @Name, Surname = @Surname, SONbr = @SONbr WHERE Id = @Id"
-- however if the @Source = 'a' the returned SQL will be
-- "update TestTable set Name = @Name, Surname = @Surname, SONbr = @SONbr, Age = @Age WHERE Id = @Id"
-- As you can see, in case of 'i', it will NOT return Age = @Age
set @sql = dbo.func_UpdateOrInsert('TestTable', @Source)
-- When this statement is executed, the error I get is 'scalar @Name does not exist'
exec (@sql)
I've commented on the operation.
The problem is obvious, I would have expected that @Id, @Name, @Surname etc... would bind automatically to the corresponding field names [Id], [Name], [Surname] etc in the context of the stored procedure... however, this is not the case.
Is there any way I can bind the parameters to a dynamically built SQL statement?