Sql 联合内的子查询

Sql 联合内的子查询,sql,sql-server,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, @loc

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

@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)
问题在于,并非所有记录在location=1的原始表中都有条目,因此当@location参数为null时,它们会被忽略。理想情况下,我会如下调整查询的最后一行,但语法不起作用:

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

如果输入参数不存在,有没有关于如何获取所有记录(无论是否为null)的建议?

我想这就是您想要的:

where (origin.location = @location or @location is null)

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

你能分享一些记录吗,比如你想要什么样的输入和输出?这里是一些数据的模型。所有黄色的行都是要返回的。Bags.Unid链接到Actions.Bag\u Unid。这很接近,但没有达到正确的目的。我想要的一个简化版本是:IF(@location!=null)origin.location=@location ELSE(origin.location=origin.location或origin.location为null),这是正确的。它确实需要保持外部联接,以便为origin.location返回null。不过,我不确定如此复杂的join子句的语法是什么,以维护上述功能。