how to late parameter bind to dynamic sql statemen

2019-09-16 04:09发布

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条回答
我欲成王,谁敢阻挡
2楼-- · 2019-09-16 04:51

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.
查看更多
登录 后发表回答