我想用下面的SQL來避免動態SQL構造:使用COALESCE來避免動態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, '%')
我想知道的是解決這個問題,即安全的方式?
編輯: 這裏是滿足我的需要忽略搜索參數,如果是零,如果存在應用它最終代碼:
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)
評論表中沒有字段可爲空,我相信我可以安全地使用提議的代碼? – krul 2010-04-20 17:39:50
@krul - 如果您沒有過濾的字段可以爲空,那麼您可以使用Coalesce,但它會導致完全匹配。如果您需要通配符匹配,那麼您需要使用我提供的第一種方法。 – Thomas 2010-04-20 17:43:40
@krul - 你當然可以混搭。對於完全匹配的列使用Coalesce,對於那些你想要通配符匹配的地方使用'@Foo Is Null或Foo Like @ Foo'構造。 – Thomas 2010-04-20 17:45:26