Hi i have a stored procedure which will have a dynamic clause, this is what my stored procedure looks like;
SELECT Comment.AddDate,Event.StartTime,Users.Name
FROM Comment
JOIN Users on Users.USERS_ID = Comment.UserID
JOIN Event ON Users.USERS_ID = Event.UserID
If i pass a variable @Name the stored procedure should then look like this;
SELECT Comment.AddDate,Event.StartTime,Users.Name
FROM Comment
JOIN Users on Users.USERS_ID = Comment.UserID
JOIN Event ON Users.USERS_ID = Event.UserID
WHERE Name = @Name
However there are cases whereby the @Name i pass in will be empty, which means i want everything returned and not based on a specific name.
Also in some cases i will also pass in an eventid, how do i go about doing this?
You can use the
COALESCEfunction in your where clause to use either the variable or the existing value, something like:WHERE Name = COALESCE(NULLIF(@Name, ''), Name)AND EventID = COALESCE(@EventID, EventID)
UPDATE:
I added the
NULLIFfunction within theCOALESCEwhich says that if the value of @Name is an empty string, treat it as NULL therefore allowing theCOALESCEfunction to work properly.