Using COALESCE to avoid dynamic SQL?
I would like to use following sql to avoid constructing sql dynamically:
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, '%')
I want to know is that safe way to approach this problem?
EDIT: Here is final code that satisfy my need to ignore search parameter if is null and applied it if is present:
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) 开发者_如何转开发
If AuthorId or CommentType are nullable, this will not work. Instead you should use an OR:
SELECT CommentID, Comment,
FROM Comments
WHERE ( @AuthorId Is Null Or AuthorId = @AuthorId )
And ( @CommentType Is Null Or CommentType Like @CommentType )
Btw, if AuthorId and CommentType are not nullable, then you can use Coalesce like so:
SELECT CommentID, Comment,
FROM Comments
WHERE AuthorId = Coalesce(@AuthorId, AuthorId)
And CommentType = Coalesce(@CommentType, CommentType )
The catch is that this is an exact match as opposed to a wildcard match like you had with LIKE.
Looks good to me but in this particular case you can ISNULL instead of COALESCE.
Just thought that I would point out that I don't think you will return any values if the AuthorID or CommentType is null.
精彩评论