首页 > 解决方案 > 如何检查表变量是否有id

问题描述

我有下表变量

DECLARE @insertedTable Table (ServiceId INT)

我从一些 SQL 查询中插入 ServiceId,

BranchServices现在我需要使用交叉连接向表中插入值@insertedTable

我写了以下 SQL 查询

INSERT INTO BranchServices
    SELECT b.BranchId
    ,its.ServiceId
    ,CASE WHEN(SELECT MIN(SortValue) FROM BranchServices WHERE FkBranchId = b.BranchId) IS NOT NULL THEN 0 END
     FROM @insertedTable its
    CROSS JOIN Branch b where b.IsActive = 1;

当表与@insertedTable表不存在时,上述查询工作正常。因为的表是主键。ServiceIdBranchServicesBranchServicesServiceId

所以现在我需要检查,如果BranchServices表已经有ServiceId我不需要运行以下查询,否则我需要运行查询。如何使用合并来做到这一点?如果是的话怎么写

INSERT INTO BranchServices
    SELECT b.BranchId
    ,its.ServiceId
    ,CASE WHEN(SELECT MIN(SortValue) FROM BranchServices WHERE FkBranchId = b.BranchId) IS NOT NULL THEN 0 END
     FROM @insertedTable its
    CROSS JOIN Branch b where b.IsActive = 1;

标签: sql-serverjoinmergecross-join

解决方案


总的猜测:

INSERT INTO BranchServices (BranchId, ServiceId, OtherColumn) --Don't know what the name of the third column is
SELECT b.BranchId,
       its.ServiceId,
       CASE WHEN (SELECT MIN(SortValue)FROM BranchServices WHERE FkBranchId = b.BranchId) IS NOT NULL THEN 0 END
FROM @insertedTable its
     CROSS JOIN Branch b
     LEFT JOIN BranchServices BS ON its.ServiceId = BS.ServiceId
WHERE b.IsActive = 1
  AND BS.ServiceId IS NULL;

旁注,空白对于编写可读代码非常重要,我建议充分利用它。


推荐阅读