sql-server - 如何检查表变量是否有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
表不存在时,上述查询工作正常。因为的表是主键。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;
解决方案
总的猜测:
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;
旁注,空白对于编写可读代码非常重要,我建议充分利用它。
推荐阅读
- firebase - 带有颤动的 Firebase 实时数据库 Rest API 中的身份验证问题
- node.js - Bencevans Screenshot-Desktop 函数在 Laravel 中使用 NodeJs
- ansible - Ansible-如何根据条件结果包含/导入剧本
- google-apps-script - Google 表格:通过受保护的表格和范围中的脚本添加编辑器
- unity3d - 如何统一通过代码将纹理分配给材质
- sql-server - 使用 pyodbc 找不到 FreeTDS 数据源
- python - 为什么 Flask pytest 不会在应用程序中发布数据?
- javascript - 如何使用 opencart 3 在特色/产品列表内容中显示/显示产品购物车数量
- android - Android Room - 执行海量表迁移后如何执行 VACUUM?
- mysql - Laravel 缓慢的 mysql 查询延迟