如何将参数动态传递给存储过程中的WHERE子句

时间:2017-01-25 06:54:08

标签: sql-server

ALTER PROCEDURE [dbo].[GetCustomers_PagerSelected]
    @PageIndex INT,
    @PageSize INT = 10,
    @SubCondition nvarchar(max),
    @RecordCount INT OUTPUT
AS  
BEGIN
    SET NOCOUNT ON;

    SELECT 
        ROW_NUMBER() OVER (ORDER BY [Plan_Id] ASC) AS RowNumber,
        [Plan_Id], [User_Id], [Plan_Name], 
        [ImageCount], [PlanPrice],
        '../User/HomePlanImage/' + CONVERT(varchar(5), User_Id ) +'/' + CONVERT(varchar(5), Plan_Id ) + '/' + CONVERT(varchar(5),1) +'.jpg' AS PlanImagePath
    INTO 
        #Results
    FROM 
        [mf_BuildingPlanDetails]
    WHERE 
        IsActive = 1 @SubCondition 

    SELECT 
        @RecordCount = COUNT(*)
    FROM 
        #Results

    SELECT * 
    FROM #Results
    WHERE 
        RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1 

    DROP TABLE #Results

1 个答案:

答案 0 :(得分:0)

这样的事可能应该做你想做的事:

ALTER PROCEDURE [dbo].[GetCustomers_PagerSelected]
    @PageIndex INT,
    @PageSize INT = 10,
    @SubCondition nvarchar(max),
    @RecordCount INT OUTPUT
AS  
BEGIN
    SET NOCOUNT ON;

    DECLARE @Sql varchar(max)

    CREATE TABLE #Results
    (
        RowNumber int,
        Plan_Id int, -- Guessing the column data type, change if needed
        User_Id int, -- Guessing the column data type, change if needed
        Plan_Name varchar(200), -- Guessing the column data type and lengthe, change if needed
        ImageCount int, -- Guessing the column data type, change if needed
        PlanPrice money, -- Guessing the column data type, change if needed
        PlanImagePath varchar(300), -- Guessing the column data type and lengthe, change if needed
    )

    SET @Sql = '
    SELECT 
        ROW_NUMBER() OVER (ORDER BY [Plan_Id] ASC) AS RowNumber,
        [Plan_Id], 
        [User_Id], 
        [Plan_Name], 
        [ImageCount], 
        [PlanPrice],
        ''../User/HomePlanImage/'' + CONVERT(varchar(5), User_Id ) + 
                                ''/'' + CONVERT(varchar(5), Plan_Id ) + 
                                ''/'' + CONVERT(varchar(5),1) + 
                                ''.jpg'' AS PlanImagePath

    FROM 
        [mf_BuildingPlanDetails]
    WHERE 
        IsActive = 1 ' + @SubCondition 

    INSERT INTO #Results 
    EXEC sp_executeSql @Sql

    SELECT 
        @RecordCount = COUNT(*)
    FROM 
        #Results

    SELECT * 
    FROM #Results
    WHERE 
        RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1 

    DROP TABLE #Results
END

,请注意,使用此类查询是安全隐患,因为它容易受到SQL injection攻击。 我强烈推荐一种不同的方法,但我不能就此提出建议,因为我没有足够的信息。