我有以下表格变量
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
表与ServiceId
表不存在BranchServices
时,上述查询工作正常。因为BranchServices
的表ServiceId
是主键。
因此,现在我需要检查,如果BranchServices
表已经具有ServiceId
,则不需要运行以下查询,否则,需要运行查询。如何使用合并?如果是的话,怎么写
INSERT INTO BranchServices
SELECT b.BranchId,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;