views:

249

answers:

1

I have a table which stores comma separated values in an NVARCHAR(MAX).

I have created a view, which uses string manipulation to convert these comma separated values into an xml list. I can then use this Xml column access each item.

The queries on this column will benefit greatly if I could index it. However, on trying to create a Primary XML index I get the message "View XmlFoo foes not have a clustered primary key. Creation of an XML index requires a clustered primary key on the view."

Is it possible to do what I'm after, and if so, how can I add a Primary Key to a View as it asks? I didn't think this was possible.

My example script is as follows.

CREATE TABLE [dbo].[Foo](
 [FooId] [int] IDENTITY(1,1) NOT NULL,
 [FooValues] NVARCHAR(MAX),
 CONSTRAINT [PK_Foo] PRIMARY KEY CLUSTERED 
 (
  [FooId] ASC
 )ON [PRIMARY]
) ON [PRIMARY]
GO

CREATE VIEW [dbo].[XmlFoo] WITH SCHEMABINDING
AS
SELECT
 FooId,
 FooValues,
 CONVERT(xml, '<FooValues><FooValue>' + REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(FooValues, '&', '&amp;'), '>', '&gt;'), '<', '&lt;'), '"', '&quot;'), '''', '&apos;'), ',', '</FooValue><FooValue>') + '</FooValue></FooValues>') AS XmFoolValues
FROM
 [dbo].[Foo]
GO

INSERT INTO XmlFoo (FooValues) VALUES ('A,B,C')
INSERT INTO XmlFoo (FooValues) VALUES ('1,2')
INSERT INTO XmlFoo (FooValues) VALUES ('X,Y')
INSERT INTO XmlFoo (FooValues) VALUES ('I')
INSERT INTO XmlFoo (FooValues) VALUES ('9,8,7,6,5')
GO
SELECT * FROM XmlFoo
A: 

Ok, I've answered my own question. The error message is obviously a red herring, instead of just saying you can't index an xml column on a view it mentions a primary key!

You cannot create an XML index, either primary or secondary, on an xml column in a view, on a table-valued variable with xml columns, or xml type variables.

link texthttp://technet.microsoft.com/en-us/library/bb934097.aspx

Robin Day