0

FieldMapping テーブルといくつかのビジネス ルールに基づいて、T-SQL ステートメントを動的に構築しようとしています。

EXEC (@Sql)簡単に言うと、ストアド プロシージャのように実行する varchar(max) として 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