SQL查询获取匹配的记录否则为NULL记录

时间:2016-04-22 20:10:28

标签: sql-server sql-server-2008

ColA    ColB    ColC

123     Null    Null

120     Null    Null

Null    1       2

Declare @ColA as Int = 123

--Rough draft, this doesn't work though

--I'm going to pass this above variable to SQL query..

Select *

from @TblA

Where @ColA = ColA or (@ColA <> ColA and ColA is Null)

需要一个SQL语句

  1. 如果ColA上有匹配项,则只获取ColA的匹配记录

  2. 如果ColA上没有匹配项,则只在Col A中获取Null记录

2 个答案:

答案 0 :(得分:1)

您可以尝试以下查询:

SELECT * FROM @TblA 
WHERE @ColA=ColA  AND EXISTS(SELECT 1 FROM @TblA WHERE @ColA=ColA)
UNION 
SELECT * FROM @TblA 
WHERE ColA IS NULL AND NOT EXISTS (SELECT 1 FROM @TblA WHERE @ColA=ColA)

这相当于

IF EXISTS(SELECT 1 FROM @TblA WHERE @ColA=ColA)
    SELECT * FROM @TblA WHERE @ColA=ColA 
ELSE 
    SELECT * FROM @TblA WHERE ColA IS NULL 

根据您的以下更新

  

是的,有2个变量@ColA和@ColB。 1.如果@ColB值匹配,则获取@ColA = ColA以及ColB = @ColB的记录以及ColB的Null值(如果有)但ColA必须具有完全匹配且没有任何不匹配或空值

更新后的查询:

SELECT * FROM @TblA 
WHERE 
 @ColA=ColA  AND 
 ISNULL(ColB, @ColB)= @ColB AND 
 EXISTS(SELECT 1 FROM @TblA WHERE @ColA=ColA)
UNION 
SELECT * FROM @TblA 
WHERE 
  ColA IS NULL AND 
  ISNULL(ColB, @ColB)= @ColB AND 
  NOT EXISTS (SELECT 1 FROM @TblA WHERE @ColA=ColA)

答案 1 :(得分:0)

我认为这会起作用

Where isnull(ColA,@ColA) = @ColA

测试代码返回2条记录,匹配​​为1和null

DECLARE @testTbl TABLE (colA INT, colB INT, colC INT)

INSERT INTO @testTbl (colA, colB, colC) VALUES  (1, 2, 3)
INSERT INTO @testTbl (colA, colB, colC) VALUES  (4, 5, 6)
INSERT INTO @testTbl (colA, colB, colC) VALUES  (null, 7, 8)

DECLARE @colA INT
SET @colA = 1

SELECT * FROM @testTbl WHERE ISNULL(colA, @colA) = @colA