传递Non-Null参数在SQL Server中返回NULL记录

时间:2012-10-30 09:15:25

标签: sql-server ssrs-2008 reporting-services

我最近发布了一个关于如何在SQL Server Reporting Services中处理NULL值的问题。问题位于Handle NULL values in SQL Server Reporting Services

应用WHERE @MyParam=MyCol OR @MyParam IS NULL面临一个问题,即如果我选择单个NON-NULL值(从下拉列表中传递并在SQL Server中传递),这也会带来NULL值记录。它应该只带来Non NULL值的记录。

如果选择了NON-NULL记录,应该采取什么措施来避免NULL记录?

1 个答案:

答案 0 :(得分:0)

您正在寻找的是异或(XOR):

-- Exclusive OR is an either/or combination which, 
-- using => as "is defined as" symbol, can be shown as:
-- 
-- x XOR y => (x AND (NOT y)) OR ((NOT x) AND y)

-- x => @MyParam = MyCol  
-- y => @MyParam IS NULL



-- DECLARE @MyParam NVARCHAR(32) = 'MC1,MC2'; -- returns two lines
-- DECLARE @MyParam NVARCHAR(32) = 'MC1';     -- returns one line
   DECLARE @MyParam NVARCHAR(32) =  NULL;     -- returns one line


DECLARE @MyParamXML XML = N'<root><r>' + replace(@MyParam,',','</r><r>') + '</r></root>'

;WITH   SOExample AS
(
    SELECT cast('MC1' AS NVARCHAR(12)) AS MyCol, 'Line 1'    AS MyCol2 UNION ALL
    SELECT      'MC2'                          , 'Line 2'              UNION ALL
    SELECT       NULL                          , 'Line NULL'
)
SELECT * from SOExample 
WHERE
       (@MyParam IS NULL     AND ISNULL(MyCol,'<NULL Value>') = '<NULL Value>') 
    OR (@MyParam IS NOT NULL AND 
        SOExample.MyCol IN 
            (SELECT SSRSlist.MyParams.value('.','NVARCHAR(32)') as MyParam 
             FROM   @MyParamXML.nodes('//root/r') as SSRSlist(MyParams)))