SQL-如果表中存在值,如何返回布尔值

时间:2019-05-24 16:34:06

标签: sql sql-server

我有一堆值(包裹),我需要检查数据库以确保它们都已经存在。有时这些包裹有100个。我想基本上返回一个true或false的值,这样我就可以找出哪个不存在并解决该特定包裹。日期方面是我需要始终按上一年过滤。我对SQL非常了解,因此感谢您的帮助。

我已经尝试过了:

SELECT *,
CASE WHEN EXISTS (SELECT * FROM Property WHERE taxyear = YEAR(GETDATE()) - 1 and (parcel in 
('1719309002000',
 '1024247013000',
 '1024247008000',
 '1024247001000'))
 THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT) END AS ExistsStatus
 FROM Property

SELECT Parcel, Powner, taxyear, 
CASE WHEN taxyear = YEAR(GETDATE()) - 1 and (parcel in 
('1719309002000',
 '1024247013000',
 '1024247008000',
 '1024247001000'
)) 
THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT) END AS result_field
FROM Property;

它只是遍历表中的每个地块,放置0或1,我只想要得到的值的结果。

4 个答案:

答案 0 :(得分:1)

您基本上想创建一个包含要检查的输入数据的派生表,因为仅将结果限制为要搜索的ID永远不会给您错误的回报。不会有不匹配的值的行。

通过执行此操作,您将从一个包含所有要查找的宗地编号的表开始,然后向左联接真实数据,以使联接时不丢失任何行。最后,CASE语句检查联接是否成功连接了现有行。

您会注意到此派生表是由一系列UNION语句创建的-本质上是将行重复粘贴在一起以创建内存表。您可以通过实际创建“临时表”来进行不同的操作,但是我发现在没有任何中间处理的情况下,此方法会稍快一些。

SELECT InputTable.parcel, (CASE WHEN Property.parcel IS NOT NULL THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT) END) AS ExistsStatus
FROM (
  SELECT '1719309002000' AS parcel UNION
  SELECT '1024247013000' UNION
  SELECT '1024247008000' UNION
  SELECT '1024247001000'
) AS InputTable
LEFT JOIN Property ON Property.parcel = InputTable.parcel AND Property.taxyear = YEAR(GETDATE()) - 1

答案 1 :(得分:1)

我建议使用exists值列表。这样可以防止结果集中出现重复项:

SELECT v.parcel,
       (CASE WHEN EXISTS (SELECT 1
                          FROM Property p
                          WHERE p.taxyear = YEAR(GETDATE()) - 1 AND
                                p.parcel = v.parcel
                         ) 
             THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT)
        END) AS ExistsStatus
FROM (VALUES ('1719309002000'),
             ('1024247013000'),
             ('1024247008000'),
             ('1024247001000')
     ) v(parcel)

答案 2 :(得分:0)

将您的值放入一个临时表中,然后与Property表进行外部联接。像这样...

Create Table #MyParcels( ParcelNumber bigint);
INSERT #MyParcles VALUES ('1234567890'), ('2345678901'), ....

SELECT ParcelNumber, CASE WHEN parcel is null THEN 0 ELSE 1 END as [Exists] FROM #MyParcels LEFT OUTER JOIN Property ON ParcelNumber = parcel

这将为#MyParcels中的每条记录返回1行,并以0/1指示它是否存在于Property中。

答案 3 :(得分:0)

您可以使用UNION操作来实现。类似于以下查询:

SELECT Parcel, MAX(result_field) AS result_field
FROM
(
  SELECT 
    Parcel,
    1 AS result_field -- exists in Property table, so value is 1
  FROM Property
  WHERE TaxYear = YEAR(GETDATE() -1)

  UNION

  -- create a temporary table with your given Parcels
  SELECT 
    Parcel,
    0 AS result_field -- doesn't exist in Property table, So it's 0
  FROM (
   VALUES
     ('1719309002000'),
     ('1024247013000'),
     ('1024247008000'),
     ('1024247001000')
   ) AS T (Parcel)

) AS ResultTable
GROUP By Parcel

这是工作中的dbfiddle

希望这会有所帮助。谢谢!