2016-01-28 56 views
1

存儲過程我寫了這個程序,並定義了兩個字符串作爲它的參數:Exec用兩個字符串參數

CREATE PROCEDURE [dbo].[spo_SelectTable1sDynamic] 
    @WhereCondition nvarchar(500), 
    @OrderByExpression nvarchar(250) = NULL 
AS 
    SET NOCOUNT ON 
    SET TRANSACTION ISOLATION LEVEL READ COMMITTED 

    DECLARE @SQL nvarchar(3250) 

    SET @SQL = 'SELECT 
        [col1], [col2], [col3], [col4] 
       FROM 
        [dbo].[Table1] 
       WHERE 
       ' + @WhereCondition 

    IF @OrderByExpression IS NOT NULL AND LEN(@OrderByExpression) > 0 
    BEGIN 
     SET @SQL = @SQL + 'ORDER BY ' + @OrderByExpression 
    END 

    EXEC sp_executesql @SQL 

我傳遞了兩個字符串爲@whereconditio@OrderByExpression參數。

如何執行此存儲過程?我用這個代碼,但得到一個錯誤:

的所有代碼
EXECUTE spo_SelectTable1sDynamic N'col1='book'' , N'col1 ' 
+2

** [可能的SQL注入](https://msdn.microsoft.com/en-us/libra ry/ms161953%28v = sql.105%29.aspx)**特別是'@ wherecondtition'完全以字符串形式傳遞 – lad2025

+0

如何解決這個問題? – programmer138200

+0

好................ – programmer138200

回答

3

首先是SQL Injection攻擊非常脆弱。

SELECT * FROM tbl WHERE @condition是罵:

If you are considering to write the procedure

CREATE PROCEDURE search_sp @condition varchar(8000) AS  
SELECT * FROM tbl WHERE @condition 

Just forget it. If you are doing this, you have not completed the transition to use stored procedure and you are still assembling your SQL code in the client.

可能的解決方案是使用動態搜索條件和避免動態SQL都:

CREATE PROCEDURE [dbo].[spo_SelectTable1sDynamic] 
    @col1 NVARCHAR(1000), -- depending on business cases 
    @col2 INT ..., 
    @sortColumn SYSNAME 
AS 
BEGIN 
    SELECT .... 
    FROM table ... 
    WHERE (col1 = @col1 OR @col1 IS NULL) 
    AND (col2 = @col2 OR @col2 IS NULL) ... 
    ORDER BY 
    CASE @sortColumn 
      WHEN 'col1' THEN col1 
      WHEN 'col2' THEN col2 
      ... 
    END 
END 

用戶可以稱其爲:

EXEC [dbo].[spo_SelectTable1sDynamic] @col1 = 'aaa' 
EXEC [dbo].[spo_SelectTable1sDynamic] @col2 = 10 
EXEC [dbo].[spo_SelectTable1sDynamic] @col1 = 'bbb', @col2 = 16 
-- or even 
EXEC [dbo].[spo_SelectTable1sDynamic 
-- to get all possible rows without any filter 
+0

非常感謝。這是一個很好的答案 – programmer138200