當(dāng)我寫下如下sql語(yǔ)句時(shí),我得到了輸入@c參數(shù)時(shí)想得到的結(jié)果集。
select * from @tb t where t.id in (select id from tb where f = @c)
但如果有@a,@b,@c,而它們分別想從@tb中得到不同的結(jié)果集,例如
復(fù)制代碼代碼如下:
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,最后一次性查詢
--構(gòu)造@tb
select * from @tb
假如我已經(jīng)通過@a,@b得到了一種@tb結(jié)果集,當(dāng)我再次使用@c進(jìn)行條件判斷時(shí),這樣就會(huì)覆蓋剛才的結(jié)果。
可以采用“刪除不符合條件的記錄”的方法來(lái)做,由于@tb已經(jīng)得到了@a,@b想得到的結(jié)果,所以只要?jiǎng)h除掉不符合@c的結(jié)果就行了。完。
復(fù)制代碼代碼如下:
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