Created
May 22, 2017 06:29
-
-
Save davidsheardown/4fdef9c43d0eef30cc423c25eb5de46b to your computer and use it in GitHub Desktop.
MS SQL Proc to pass in optional parameters and return based on the combination required
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Allows you to pass in option params and select based on the combination | |
-- The trick is the WHERE (condition in brackets) AND combination below | |
ALTER PROCEDURE [dbo].[FetchTaskHistoryByClientId] | |
@ClientId int, | |
@TaskId int = 0, | |
@TaskCompleted bit = 0, | |
@TaskFailed bit = 0 | |
AS | |
BEGIN | |
SET NOCOUNT ON; | |
SELECT | |
Clients.Name, | |
TaskStats.TaskFailed, | |
TaskStats.TaskCompleted, | |
TaskStats.TaskCancelled, | |
TaskStats.TaskFaulted, | |
TaskStats.TaskCentreStatusCode, | |
case when TaskStats.TaskCompleted = 1 then 'Completed' else 'Failed' end as TaskStatus, | |
TaskStats.DateCreated, | |
Tasks.TaskDisplayName, | |
TaskStats.ParamsEntered | |
FROM | |
TaskStats | |
INNER JOIN | |
Clients ON dbo.TaskStats.ClientId = dbo.Clients.Id | |
INNER JOIN | |
Tasks ON dbo.TaskStats.TaskId = dbo.Tasks.Id | |
WHERE | |
(@TaskId = 0 OR TaskStats.TaskId = @TaskId) | |
AND | |
(@TaskCompleted = 0 OR TaskStats.TaskCompleted = @TaskCompleted) | |
AND | |
(@TaskFailed = 0 OR TaskStats.TaskFailed = @TaskFailed) | |
AND | |
Clients.Id = @ClientId |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment