喜欢动态查询

时间:2009-07-08 12:33:23

标签: sql dynamic sql-injection

我想在动态参数化查询中使用like关键字。我想保护我的查询免受SQL注入,所以我不想传递值,而是我想在执行查询时传递我的标准,

我有办法做到这一点吗?

SELECT 
  ComposeMail.ID,
  ComposeMail.DateTime, 
  ComposeMail.Subject, 
  ComposeMail.CreatedBy, 
  ComposeMail.ReceiverStatus,
  Users.Name,
  ROW_NUMBER() OVER(ORDER BY '+ @p_SortExpression +') AS Indexing
FROM 
  ComposeMail 
INNER JOIN
  Users
ON
  ComposeMail.CreatedBy = Users.ID
WHERE 
  (ToReceipientID=@p)
  AND (
    ReceiverStatus=3 
    OR ReceiverStatus=4
  )
  AND (
    (Subject Like ''%' + @p3 + '%'') 
    OR (Body Like ''%' + @p3 + '%'') 
    OR (Name Like ''%' + @p3 + '%'')
  )

这是我的动态查询字符串。我不想在这里传递这个值。

2 个答案:

答案 0 :(得分:5)

为了防止在动态查询中注入,你总是想做这样的事情(而不是在你的例子中做'+ @var +')

DECLARE @query nvarchar(2000),
        @paramList nvarchar(2000)

SET @query = 'SELECT * FROM dbo.Orders WHERE custLastName LIKE ''%'' + @custLastName + ''%'''
SET @paramList = '@custLastName varchar(30)'

EXEC SP_EXECUTESQL @query, @paramList, @custLastName

编辑:示例已更新为使用LIKE

答案 1 :(得分:0)

 WHERE        (LastName LIKE N'%' + @Family + N'%') OR
                         (RegNo LIKE N'%' + @Codemeli + N'%')

就像在动态sql查询中一样