簡體   English   中英

從存儲過程-sql-server根據布爾進行條件連接

[英]conditional join according to Boolean from stored procedure-sql- server

我有以下代碼:

with cte1 as (

select ...... from TABLE 1......
where ......
)

with cte2 as 
( 
select .... from table2....
where.....
)

select cte1.id,cte2.name,cte2.last from cte1 join cte2 on cte1.id=cte2.id

我想要的是從存儲過程中獲取布爾變量。
確實如此時,我不想進行連接,也不想計算cte2。

就像是:

if(@BollVar=false)
select cte1.id,cte2.name,cte2.last from cte1 join cte2 on cte1.id=cte2.id
else
select cte1.id,cte1.cat from cte1 
(and here I don't want cte2 to be calculated, because I don't need it)

我該怎么辦?

with cte1 as (

select ...... from TABLE 1......
where ......
)

with cte2 as 
( 
select .... from table2....
where.....
)

select cte1.id,cte2.name,cte2.last from cte1
left join
cte2 on cte1.id=cte2.id
And @BollVar = 0
Where
         @BollVar = 1
         Or cte2.id is not null

另一種方法是切換到左聯接,如果變量為true,則不返回任何行,添加一個where語句以測試變量是否為true以返回所有內容,或者當cte2.id不為null時將其設為實際需要結果時進行內部聯接。

之所以行之有效,是因為您可以放入幾乎所有您想要的對聯接條件評估為true或false的東西。

抱歉,格式化手機的首次嘗試格式不正確

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM