I have a table TableX. It contains three columns: A INT , B INT and C VARCHAR(1) (valid values for column C being the name of the columns ‘A’ or ‘B’). I need to count the number of occurrences where either of the following conditions are met:
- When
CisNULLand does contains values in eitherAorBgreater than zero. or - When
CisNOT NULL(i.e. ‘A’ or ‘B’) and the value in the specified column (AorB) is either zero orNULL.
My current stored procedure looks like
CREATE PROCEDURE ispcSomeName @NumOcc INT OUTPUT
AS
SELECT COUNT(*) AS [NumOcc]
FROM TableName
WHERE (C IS NULL
AND ((A IS NOT NULL OR A > 0) OR
(B IS NOT NULL OR B > 0)))
OR (CritCarType IS NOT NULL
AND (CASE SET @TmpColumnName = CritCareType
WHEN N'A' THEN (A IS NULL OR A <= 0)
WHEN N'B' THEN (B IS NULL OR B <= 0)))
GO
The problem is that I need to check the column that C references. That is if C = 'A', I need to check if A IS NOT NULL OR A <= 0. There is clearly an issue with the SET in the final WHERE. I have got a few of these types of SPs to author and I want to avoid complex TSQL if I can help it…
How do I dynamically get reference to the relevant column in the WHERE clause?
Thanks for your time.
1 Answer