如何检查 table 变量是否有 id

How to check if table variable have id or not

我有以下 table 变量

DECLARE @insertedTable Table (ServiceId INT)

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

现在我需要使用交叉连接将值插入 BranchServices table @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 table 与 BranchServices table 不存在 ServiceId 时,上述查询工作正常。因为 BranchServices 的 table ServiceId 是主键。

所以现在我需要检查,如果BranchServices table已经有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;

总猜测:

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;

旁注,白色 space 对于编写可读代码非常重要,我建议很好 使用它。