【发布时间】:2019-11-06 11:04:56
【问题描述】:
我有下表变量
DECLARE @insertedTable Table (ServiceId INT)
我从一些 SQL 查询中插入 ServiceId,
现在我需要使用交叉连接 @insertedTable 将值插入到 BranchServices 表中
我写了以下 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 表不存在ServiceId 与BranchServices 表相同时,上述查询工作正常。因为BranchServices的表ServiceId是主键。
所以现在我需要检查,如果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;
【问题讨论】:
-
对
BranchServices执行LEFT JOIN并检查ServiceId(在BranchServices中)的值是否为NULL? -
@Larnu 你能给我一个完整的答案吗
-
@Larnu 不,它不为空
标签: sql-server join merge cross-join