我试图动态构建基于一个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语句中的任何方式?