我想使用以下sql来避免动态构造sql:
SELECT CommentID, Comment,
FROM Comments
--if Author id is not null then filter upon author id otherwise get all comments (ignore author id)
WHERE AuthorID LIKE COALESCE(@AuthorId, '%')
--if comment type is present filter upon it, otherwise get all comments (ignore comment type condition)
AND CommentType LIKE COALESCE(@CommentType, '%')
我想知道解决这个问题的安全方法是什么?
编辑: 这是最终代码,满足我忽略搜索参数的需要,如果为null,则应用它(如果存在):
SELECT CommentID, Comment,
FROM Comments
--if @AuthorId is not null then filter upon @AuthorId otherwise get all comments (ignore author id)
WHERE AuthorID = COALESCE(@AuthorId, AuthorID)
--if @CommentType is present filter upon it, otherwise get all comments (ignore comment type condition)
AND CommentType = COALESCE(@CommentType, CommentType)
答案 0 :(得分:3)
如果AuthorId或CommentType可以为空,则不起作用。相反,你应该使用OR:
SELECT CommentID, Comment,
FROM Comments
WHERE ( @AuthorId Is Null Or AuthorId = @AuthorId )
And ( @CommentType Is Null Or CommentType Like @CommentType )
顺便说一句,如果AuthorId和CommentType不可为空,那么你可以像这样使用Coalesce:
SELECT CommentID, Comment,
FROM Comments
WHERE AuthorId = Coalesce(@AuthorId, AuthorId)
And CommentType = Coalesce(@CommentType, CommentType )
问题在于,这是一个完全匹配,而不是像LIKE一样的通配符匹配。
答案 1 :(得分:0)
对我来说很好,但在这种特殊情况下你可以使用ISNULL而不是COALESCE。
我想我会指出,如果AuthorID或CommentType为null,我认为你不会返回任何值。