开发者

Index View Index Creation Failing

I'm trying to create an index on a view and it keeps failing, I'm pretty sure its b/c I'm using an alias for the column. Not sure how or if I can do it this way. Below is a simplified scenario.

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 '.'.

Anyone know how to create an indexed view using aliased columns please let me know.


try using brackets around the column name because the name is not a valid column name

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

Also indexed views require 5 or so SET options to be on, more info here: http://msdn.microsoft.com/en-us/library/ms191432.aspx


How about a comma between the two columns???

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

And I probably wouldn't really use "Contract.ContractID" as my alias..... the dotted notation has special meaning in SQL Server (database.schema.object) - so I would avoid anything that could cause trouble there.....

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


Why are you aliasing the tables if you are simply going to re-alias the columns back to the original?? Just do

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

And yes, you were missing a comma.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜