0
CREATE TABLE Storage
(
    ID INT IDENTITY(1,1) PRIMARY KEY,
    data XML NOT NULL
)

GO

INSERT INTO Storage(data) 
VALUES('
<footballteams>   
    <team manager="Benitez">     
        <name>Liverpool</name>     
        <ground>Anfield</ground>   
    </team>   
    <team manager="Mourinho">     
        <name>Chelsea</name>     
        <ground>Stamford Bridge</ground>   
    </team>   
    <team manager="Wenger">     
    <name>Arsenal</name>     
        <ground>Highbury</ground>   
    </team> 
</footballteams>'); 
----------------------------------------
GO

CREATE VIEW FootballView WITH SCHEMABINDING AS 
(    
    SELECT            
        TeamName = Team.TeamNode.value('(name)[1]', 'varchar(100)'),              
        Manager = Team.TeamNode.value('(@manager)', 'varchar(100)'),              
        Ground = Team.TeamNode.value('(ground)[1]', 'varchar(100)')    
    FROM         
        dbo.Storage S          
        CROSS APPLY DATA.nodes('/footballteams') AS Teams(TeamsNode)
        CROSS APPLY data.nodes('/footballteams/team') AS Team(TeamNode)
)
GO
CREATE UNIQUE CLUSTERED INDEX TeamNameInd ON FootballView(TeamName)

-

Error Message: Cannot create index on view "CF.dbo.FootballView" because it contains an APPLY. Consider not indexing the view, or removing APPLY.

我意识到,事实上,不能为此视图创建索引,因为使用了 CROSS APPLY。任何人都可以为此提出解决方法吗?因为在处理大量 XML 数据时,使用这种没有索引的视图太慢了。

编辑:

有什么办法可以索引 XML 本身吗?

4

1 回答 1

0

您可以通过将 XML 数据解析为 SQL 关系表并使用简单触发器使表保持同步来解决此问题(并且可能获得更好的性能)。以下脚本是如何完成它的示例,我希望它对您的情况有用:

CREATE TABLE Storage (
  id INT IDENTITY(1,1) PRIMARY KEY,
  data XML NOT NULL
);

CREATE TABLE FootballTable (
  id INT,
  teamName varchar(100),
  manager varchar(100),
  ground varchar(100)
);
GO

CREATE TRIGGER TG_INS_Storage ON Storage
FOR INSERT, UPDATE, DELETE AS
BEGIN
  DELETE FootballTable WHERE id IN (SELECT dlt.id FROM deleted dlt);

  INSERT FootballTable (id, teamName, manager, ground)
  SELECT ins.id,
    TeamName = Team.TeamNode.value('(name)[1]', 'varchar(100)'),
    Manager  = Team.TeamNode.value('(@manager)', 'varchar(100)'),
    Ground   = Team.TeamNode.value('(ground)[1]', 'varchar(100)')
  FROM inserted ins
  CROSS APPLY ins.data.nodes('/footballteams/team') AS Team(TeamNode);
END

INSERT INTO Storage(data) 
VALUES('
<footballteams>
  <team manager="Benitez"><name>Liverpool</name><ground>Anfield</ground></team>   
  <team manager="Mourinho"><name>Chelsea</name><ground>Stamford Bridge</ground></team>   
  <team manager="Wenger"><name>Arsenal</name><ground>Highbury</ground></team> 
</footballteams>');
GO
SELECT * FROM FootballTable;
于 2012-06-29T16:09:04.527 回答