2010-06-09 116 views
1

我想在視圖上創建一個索引,並且它保持失敗,我很確定它的B/C我使用列的別名。不知道如何或如果我可以這樣做。以下是一個簡化的場景。索引視圖索引創建失敗

CREATE VIEW v_contracts WITH SCHEMABINDING 
AS 
SELECT 
    t1.contractid as 'Contract.ContractID' 
    t2.name as 'Customer.Name' 
    FROM contract t1 
    JOIN customer t2 
    ON t1.contractid = t2.contractid 
GO 

CREATE UNIQUE CLUSTERED INDEX v_contracts_idx ON v_contracts(t1.contractid) 
GO 
--------------------------- 
Incorrect syntax near '.'. 

CREATE UNIQUE CLUSTERED INDEX v_contracts_idx ON v_contracts(contractid) 
GO 
--------------------------- 
Column name 'contractid' does not exist in the target table or view. 

CREATE UNIQUE CLUSTERED INDEX v_contracts_idx ON v_contracts(Contract.ContractID) 
GO 
--------------------------- 
Incorrect syntax near '.'. 

任何人都知道如何使用別名列創建索引視圖,請讓我知道。

回答

2

嘗試使用括號因爲這個名字是不是一個有效的列名

CREATE UNIQUE CLUSTERED INDEX v_contracts_idx 
ON v_contracts([Contract.ContractID]) 
GO 

而且索引視圖需要5個左右的SET選項打開,更多的信息在這裏:http://msdn.microsoft.com/en-us/library/ms191432.aspx

+0

是的,這是它的!我無法相信我忘記了[]。我在各地使用它們。謝謝! – aBetterGamer 2010-06-10 15:50:00

1

逗號兩列之間的關係如何?

SELECT 
    t1.contractid as 'Contract.ContractID' -- <=== comma missing here 
    t2.name as 'Customer.Name' 

,我可能不會真的用「Contract.ContractID」作爲我的別名.....點號在SQL Server中具有特殊意義(database.schema.object) - 所以我會避免任何可能導致麻煩有.....周圍的列名

CREATE VIEW v_contracts WITH SCHEMABINDING 
AS 
    SELECT 
    t1.contractid as 'ContractID' , -- comma here at the end!! 
    t2.name as 'CustomerName' 
    FROM contract t1 
    JOIN customer t2 ON t1.contractid = t2.contractid 
GO 

CREATE UNIQUE CLUSTERED INDEX v_contracts_idx ON v_contracts(ContractID) 
GO 
+0

是的,我的示例中缺少逗號,但不是實際的代碼。不幸的是,我必須使用點符號b/c來替換列名,這就是我們的自定義ORM如何將字段映射到對象屬性並創建關係。 – aBetterGamer 2010-06-10 15:43:46

0

爲什麼你別名表,如果你只是想重新將別名列回原?只是做

CREATE VIEW v_contracts WITH SCHEMABINDING 
AS 
SELECT 
    Contract.ContractID, 
    Customer.Name 
    FROM contract 
    JOIN customer 
    ON contract.contractid = customer.contractid 
GO 

是的,你錯過了一個逗號。

+0

試圖讓它明顯,我使用兩個表。 – aBetterGamer 2010-06-10 15:45:20