如何后期绑定参数为动态SQL语句在存储过程(how to late parameter bind t

2019-11-02 15:42发布

我试图动态构建基于一个FieldMapping表和一些业务规则的T-SQL语句。

削减长话短说,我将返回的SQL语句为VARCHAR(最大值),我将要执行的功能EXEC (@Sql)在我的存储过程。

请允许我用一个测试表演示

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)

我曾经评论的操作。

问题是显而易见的,我本来预计@Id,@Name,@Surname等...将自动绑定到相应的字段名称[ID],[名],[姓氏]等在存储过程的情况下。 .. 然而,这种情况并非如此。

有没有我可以将参数绑定到一个动态生成的SQL语句中的任何方式?

Answer 1:

该sp_executesql的存储过程执行此操作

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.


文章来源: how to late parameter bind to dynamic sql statement in a stored procedure