how to late parameter bind to dynamic sql statement in a stored procedure

天大地大妈咪最大 提交于 2019-12-25 03:15:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!