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, '&', '&'), '>', '>'), '<', '<'), '"', '"'), '''', '''), ',', '</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