0

我正在尝试基于 FieldMapping 表和一些业务规则动态构建 T-SQL 语句。

长话短说,我有一个函数将 SQL 语句作为 varchar(max) 返回,我将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]、[Name]、[Surname] 等。 .. 然而,这种情况并非如此。

有什么方法可以将参数绑定到动态构建的 SQL 语句?

4

1 回答 1

3

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.
于 2013-11-13T01:06:25.190 回答