首页 > 数据库 > MsSQL

根据多条件查询临时表 想得到不同结果集的方法

admin MsSQL 2022-02-09 21:48:02 多条件查询   不同结果集"
当我写下如下sql语句时,我得到了输入@c参数时想得到的结果集。
select * from @tb t where t.id in (select id from tb where f = @c)
但如果有@a,@b,@c,而它们分别想从@tb中得到不同的结果集,例如
复制代码 代码如下:
if @a is not null
begin
--得到@a想得到的
end
if @b is not null
begin
--得到@b想得到的
end
if @c is not null
begin
--得到@c想得到的
end

这样做好像没什么问题,但如果@a和@b是一起的,甚至是@a,@b,@c,@d,@e,@f等等N多种条件组合,这样就不好办了。所以必须先build好@tb,最后一次性查询
--构造@tb
select * from @tb
假如我已经通过@a,@b得到了一种@tb结果集,当我再次使用@c进行条件判断时,这样就会覆盖刚才的结果。
可以采用“删除不符合条件的记录”的方法来做,由于@tb已经得到了@a,@b想得到的结果,所以只要删除掉不符合@c的结果就行了。完。
复制代码 代码如下:
if @c is not null
begin
delete c from @tb c where c.id not in (select id from tb where f = @c)
end
select * from @tb
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。
本文地址:/shujuku/MsSQL/100254.html

留言与评论(共有 0 条评论)
   
验证码:

潘少俊衡

| 桂ICP备2023010378号-4

Powered By EmpireCMS

爱享小站

中德益农

谷姐神农

环亚肥料

使用手机软件扫描微信二维码

关注我们可获取更多热点资讯

感谢潘少俊衡友情技术支持