动态查询'in子句'参数不起作用

问题描述 投票:0回答:1

我正在存储过程中使用动态查询。我传递了两个参数,一个用于“等于大小写”,另一个用于“以防万一”。如图所示,在大小写相等的情况下,大小写不起作用。有什么办法可以在查询中放入“万一”的参数。

这是我进行更好编辑的步骤。

    Alter PROCEDURE [dbo].[Test_In_Clause]

    -- Add the parameters for the stored procedure here
    @name nvarchar(50) = NULL,
    @class nvarchar(50) = NULL


AS
BEGIN

    declare 
    @sql nvarchar(max),
    @ParameterDef NVARCHAR(500)

    set @ParameterDef = '@name nvarchar(50),
                        @class nvarchar(50)'

    set @sql  = 'Select * from aaa_Students where Name = @name and Class in @class'
    print @sql
    exec sp_Executesql @sql, @ParameterDef, @name = @name, @class = @class


END

PS:我不想使用Select * from aaa_Students where Name = @name and Class in ('+ @class +')格式来保护SQL注入。

Stored Procedure

Executing stored procedure

sql stored-procedures parameter-passing dynamicquery in-clause
1个回答
0
投票

尝试一下:

    alter PROCEDURE [dbo].[Test_In_Clause]

    -- Add the parameters for the stored procedure here
    @name nvarchar(50) = NULL,
    @class nvarchar(50) = NULL


AS
BEGIN

    declare 
    @sql nvarchar(max),
    @ParameterDef NVARCHAR(500)

    set @ParameterDef = N'@name nvarchar(50),
                        @class nvarchar(50)'

    set @sql  = 'Select * from aaa_Students where Name = @name and Class in (@class)'
    print @sql
    execute sp_Executesql @sql, N'@name nvarchar(50),@class nvarchar(50)', @name = @name, @class = @class
© www.soinside.com 2019 - 2024. All rights reserved.