Est-il possible de définir une variable locale pour autoriser n'importe quelle valeur?

J'ai une série de requêtes qui sont utilisées pour l'assurance qualité. Normalement, nous limitons l' organizationid à une valeur unique, mais parfois nous voulons renvoyer tous les organizationid . Est-il possible de le faire sans avoir à commenter tous les @orgid dans la requête?

Exemple:

 DECLARE @REPSD DATETIME = '10-01-2014'; DECLARE @REPED DATETIME = '09-30-2015'; DECLARE @orgid BIGINT = 5 SELECT patientid, MAX (dateofobservation) sbp_date INTO #t1 FROM dbo.patientobservation (nolock) WHERE observationcode IN ('8479-8','8480-6','8459-0','8460-8','8461-6') AND dateofobservation >= @REPSD AND dateofobservation <= @REPED AND organizationid = @orgid 

Probablement vous voulez:

 DECLARE @REPSD DATETIME = '10-01-2014'; DECLARE @REPED DATETIME = '09-30-2015'; DECLARE @orgid BIGINT = NULL SELECT patientid, MAX (dateofobservation) sbp_date INTO #t1 FROM dbo.patientobservation (nolock) WHERE observationcode IN ('8479-8','8480-6','8459-0','8460-8','8461-6') AND dateofobservation >= @REPSD AND dateofobservation <= @REPED AND organizationid = ISNULL(@orgid,organizationid); 

ou:

 SELECT patientid, MAX (dateofobservation) sbp_date INTO #t1 FROM dbo.patientobservation (nolock) WHERE observationcode IN ('8479-8','8480-6','8459-0','8460-8','8461-6') AND dateofobservation >= @REPSD AND dateofobservation <= @REPED AND ( (organizationid = @orgid AND @orgid IS NOT NULL) OR @orgid IS NULL ) 

En utilisant JamieD77 suggestion qui est équivalente à ci-dessus mais plus simple et plus compact:

 AND (@orgid IS NULL OR organizationid = @orgid) 

Vous devriez envisager d'utiliser le troisième exemple, car le premier n'est pas-SARGable, donc l'optimiseur de requêtes n'utilisera pas d'index sur cette colonne s'il existe.