将sp_executesql与动态参数一起使用

时间:2016-07-07 09:38:26

标签: sql-server

CREATE PROCEDURE GetUserDetails
(
    @ParameterListWithDataType  VARCHAR(MAX),
    @ParameterNameList      VARCHAR(MAX),
    @ParameterValues        VARCHAR(MAX),
    @WhereCondition     VARCHAR(MAX)
)
AS
BEGIN
    DECLARE @sql NVARCHAR(4000)
    SET @sql = ' SELECT FirstName, MiddleName, LastName, Address, Salary FROM UserDetails WHERE ' + @WhereCondition 

    EXEC sp_executesql @sql, @ParameterListWithDataType, @ParameterNameList
END

EXEC GetUserDetails @ParameterListWithDataType = '@FirstName VARCHAR(100)',  @ParameterNameList = '@FirstName', @ParameterValues = 'ABC', @WhereCondition = 'FirstName = @FirstName '

EXEC GetUserDetails @ParameterListWithDataType = '@FirstName VARCHAR(100), @LastName VARCHAR(100)',  @ParameterNameList = '@FirstName,@LastName', @ParameterValues = '''ABC'', ''XYZ''', @WhereCondition = 'FirstName = @FirstName OR LastName = @LastName'

EXEC GetUserDetails @ParameterListWithDataType = '@FirstName VARCHAR(100), @LastName VARCHAR(100), @MiddleName VARCHAR(100)',  @ParameterNameList = '@FirstName,@LastName,@MiddleName', @ParameterValues = '''ABC'', ''XYZ'', ''DEF''', @WhereCondition = 'FirstName = @FirstName OR LastName = @LastName OR MiddleName = @MiddleName'

有这样做的方法吗?因为搜索条件将是动态的。请给出您的评论或给我替代解决方案,以便将sp_executesql与动态参数一起使用。

先谢谢。

1 个答案:

答案 0 :(得分:0)

希望此查询可以帮助您,

CREATE PROCEDURE GetUserDetails
(
    @FirstName  VARCHAR(MAX),
    @LastName      VARCHAR(MAX),
    @MiddleName        VARCHAR(MAX)
)
AS
BEGIN
    DECLARE @sql NVARCHAR(4000)
    DECLARE @WhereCondition VARCHAR(MAX)

    SET @WhereCondition = ' WHERE 1 = 1'+case when @FirstName is null then '' else ' or FirstName = '+ @FirstName end+
                            case when @LastName is null then '' else ' or LastName = '+ @LastName end+
                            case when @MiddleName is null then '' else ' or MiddleName = '+ @MiddleName
                          end

    SET @sql = ' SELECT FirstName, MiddleName, LastName, Address, Salary FROM UserDetails' + @WhereCondition 

    EXECUTE(@sql)

END

只需使用

执行该过程
EXEC GetUserDetails 'ABC','XYZ','DEF'