2015-09-03 59 views
-1

我有一個需要在多個站點運行的SQL查詢,查詢將與「站點ID」相同,站點ID存儲在另一個表中每個數據庫,所以我認爲它會更容易自動化,並寫入查詢,以獲取正確的位置在where子句中的siteid而不是更改查詢20次。如何使用where子句中的列條目篩選查詢

我的查詢是:

Select * 
from customers 
where bactive = 'true' and siteid = 'Site1' 

網站存儲在表中的「帳戶」所以,我想我可以做這樣的事情:

select * 
from customers 
where bactive = 'true' and siteid = database.dbo.accounts.siteid 

這沒有奏效。

任何幫助表示讚賞。

+1

但是應該使用哪個database.dbo.accounts.siteid?所有這些,還是隻有一個? – jarlh

+0

您需要在Select Clasue –

回答

1

。如果您的網站ID與您的服務器名稱,你可以嘗試這樣的:

select * 
from customers 
where bactive = 'true' and siteid = @@ServerName 

其中@@ serverName是SQL Server的系統名稱I nstance

如果您的網站ID從服務器實例名稱不同,您可以添加實例名稱爲您的賬戶表中的屬性,所以你可以做你的實例名稱,網站ID之間的鏈接:

select * 
from customers 
where bactive = 'true' and siteid = (SELECT Tbl_Account.siteid From Tbl_Account Where Tbl_Account.serverName = @@ServerName) 
0

試試這個 如果數據庫是同一臺服務器

select Customer.* from customers c 
INNER JOIN database.dbo.accounts s ON c.siteid = c.siteid  
where c.bactive = 'true' 

。如果數據庫是其他服務器

select Customer.* from customers c 
INNER JOIN ServerName.database.dbo.accounts s ON c.siteid = c.siteid  
where c.bactive = 'true' 
+0

@ jarlh..yup.need中添加「customer。*」以將其添加到內連接中。現在將編輯它 –