coalesce中的子查询

时间:2017-05-03 16:40:23

标签: sql sql-server

我目前正在使用合并查询在输入参数不存在时返回所有值,如下所示:

@unid int

SELECT
  *
FROM Bag_Dim
LEFT JOIN Bag_Action_Join
  ON Bag_Dim.Unid = Bag_Action_Join.Bag_Unid
WHERE Bag_Dim.Unid = COALESCE(@unid, [bag_dim].[unid])

我想在返回参数中添加一个额外的字段,这些字段仅出现在某些记录中,因此代码修改如下:

@unid int,
@location int

SELECT
  *,
  origin.location
FROM Bag_Dim
LEFT JOIN Bag_Action_Join
  ON Bag_Dim.Unid = Bag_Action_Join.Bag_Unid
LEFT JOIN Bag_Action_Join AS origin
  ON Bag_Dim.Unid = origin.Bag_Unid
  AND origin.action = 1
WHERE Bag_Dim.Unid = COALESCE(@unid, [bag_dim].[unid])
AND origin.location = COALESCE(@location, origin.location)

问题是并非所有记录在origin表中都有location = 1的条目,因此当@location参数为null时它们会被省略。理想情况下,我会调整查询的最后一行,如下所示,但语法不起作用:

WHERE origin.location = coalesce(@location,(origin.location OR origin.location IS NULL))

如果输入参数不存在,我对如何获取所有记录(无论是否为空)有任何建议?

2 个答案:

答案 0 :(得分:2)

我认为这就是你想要的:

{
    "name": "oxygen",
    "children": [
      {
        "name": "tree",
        "children": [
          {
            "name": "G2",
            "children": [
              {
                "name": "T2"
              },
              {
                "name": "T1"
              }
            ]
          },
          {
            "name": "G1",
            "children": [
              {
                "name": "T1"
              }
            ]
          }
        ]
      },
      {
        "name": "bomb",
        "children": [
          {
            "name": "GYYS",
            "children": [
              {
                "name": "T1"
              }
            ]
          }
        ]
      }
    ]
  }

答案 1 :(得分:1)

听起来您需要将新条件从WHERE子句移动到JOIN条件中。当您在查询的where子句中引用未保留的表(来自外部联接)时,您在逻辑上将外部联接转换为内部联接 - 这可能不是您想要的。