问题
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?
回答1:
The sp_executesql stored procedure does this
create procedure [dbo].[sp_TestInsert]
@Id int,
@Name varchar(20),
@Surname varchar(20),
@Age int,
@Source varchar(1)
as
declare
@sql nvarchar(max) = dbo.func_UpdateOrInsert('TestTable', @Source),
@params nvarchar(max)
= N'@Name varchar(20), @Surname varchar(20), @SONbr int, @Age int'
-- You need to get @SONbr from somewhere
exec sp_executesql @sql, @params, @Name, @Surname, @SONbr, @Age
-- note, it doesn't matter if a bound parameter isn't mentioned in the query
-- so @Age can be passed in regardless.
来源:https://stackoverflow.com/questions/19943202/how-to-late-parameter-bind-to-dynamic-sql-statement-in-a-stored-procedure