靜態的解決方案:同樣可以通過類似的東西來實現
CREATE VIEW Person.vBusinessEntityAddressWithInfo
AS
SELECT bea.AddressID,bea.AddressTypeID,bea.BusinessEntityID,bea.ModifiedDate,
a.PostalCode AS AddressPostalCode,a.City AS AddressPostalCity
FROM Person.BusinessEntityAddress bea
JOIN Person.[Address] a ON bea.AddressID=a.AddressID;
GO
-- Test #1: columns from only one table Person.BusinessEntityAddress
SELECT v.AddressID,v.BusinessEntityID
FROM Person.vBusinessEntityAddressWithInfo v
GO
-- Test #2: columns from both tables
SELECT v.AddressID,v.BusinessEntityID,v.AddressPostalCode
FROM Person.vBusinessEntityAddressWithInfo v
GO
如果我看的執行計劃,那麼我可以看到,對於Test #1
SQL Server只使用Person.BusinessEntityAddress
表(見FK elimination
;另見本answer)和Test #2
SQL Server使用兩個表:
另一個「靜態」(或多或少)解決方案:
DECLARE @Type BIT;
SET @Type=0;
SELECT bea.*,NULL AS AddressPostalCode,NULL AS AddressPostalCity
FROM Person.BusinessEntityAddress bea
WHERE @Type=0
UNION ALL
SELECT bea.*,a.PostalCode AS AddressPostalCode,a.City AS AddressPostalCity
FROM Person.BusinessEntityAddress bea
JOIN Person.[Address] a ON bea.AddressID=a.AddressID
WHERE @Type=1;
如果我執行這個查詢與@Type=0
和SET STATISTICS IO ON
那麼SQL Server將來自BusinessEntityAddress
讀取數據:
Table 'Worktable'. Scan count 0, logical reads 0
Table 'Worktable'. Scan count 0, logical reads 0
Table 'BusinessEntityAddress'. Scan count 1, logical reads 112
,當我執行相同的查詢與@Type=1
然後SQL Server將從兩個表讀取數據:
Table 'Worktable'. Scan count 0, logical reads 0
Table 'Address'. Scan count 1, logical reads 216
Table 'BusinessEntityAddress'. Scan count 1, logical reads 112
Table 'Worktable'. Scan count 0, logical reads 0
它不會忽略th e加入。它總是加入桌子。如果JoinWithT2 = 1,那麼它會進行正確的連接(在ID上),如果它是0,則加入所有記錄,從而有效地將您的連接變爲交叉連接。那是你要的嗎? – GolezTrol
請注意,當@ JoinWithT2爲0時,第一個查詢不是**等同於從T1選擇T1。*,而是成爲隱式笛卡爾連接 - 請參閱http://sqlfiddle.com/# !3/3f574/3 –
是的。實際上,如果'@ JoinWithT2'的值爲0,我會忽略連接。 –