sql - 如果没有返回行,SQL 返回默认值
问题描述
我有一个返回结果集的 SQL 脚本,如果以下脚本没有产生任何结果,则要求返回具有默认值的默认结果集。它应该与以下脚本具有相同的列名
-- Return final results
SELECT
p.worked [AccountsWorked],
p.rcmade [RPC's],
p.obtained [PTPCount],
p.amount [PTPValue],
[PreviousDayPTPValue]
FROM
@tab_performance p JOIN
dbo.user usr ON
(p.usr_code = usr.usr_code) JOIN
dbo.team tme ON
(tme.tme_id = usr.tme_id)
AND p.usr_code = @usr_code
如果没有返回行,我需要返回默认结果集。因此,所有列都应返回 NULL 或任何默认值。
我试过条件选择语句没有任何运气,我也试过@@ROWCOUNT
解决方案
您可以union all
使用默认值向现有查询添加选择,如下所示:
<your existing query>
union all
select null accounts_worked, null right_contacts_made, null ppts_obtained .....
where not exists(
select *
from @tab_performance p JOIN
dbo.TR_USR_User usr ON
(p.usr_code = usr.usr_code) JOIN
dbo.TR_TME_Team tme ON
(tme.tme_id = usr.tme_id)
AND p.usr_code = @usr_code
)
如果您不从以下内容中过滤掉任何行where
,则可以进一步简化该子句:inner joins
@tab_performance
<your existing query>
union all
select null accounts_worked, null right_contacts_made, null ppts_obtained .....
where not exists(
select *
from @tab_performance
where usr_code = @usr_code
)
推荐阅读
- ios - 移除 CoreGraphics 动画
- reactjs - 当我在 create-react-app 中输入 npm start 时如何指定自定义 URL
- python - 如何根据世代显示,x '攻击' 和 y '防御'
- javascript - 在加载组件中检查后表达式已更改
- python - 如何修复 Anaconda Jupyter Notebook 内核错误?
- javascript - 使用 React-Native 在 ScrollView 中的特定位置缩放
- php - 插入在本地工作,但不在服务器上
- laravel - 将数据传递到包含的刀片视图
- amazon-web-services - 如何为 aws_autoscaling_group 发出的现场请求应用标签?
- javascript - 如何使用 ajax 和 django 上传文件?