I am using SQL Server 2008 R2 and I have data in a format AA-BB-CCCCCCCC-DDDDDDDD-EEEE
stored in one column. I need to separate this into 5 separate columns with T-SQL inline (I don't want to create a function for this purpose, though I may look into it if there is a serious performance gain, there are permissions issues here that I would have to deal with). I am creating a view to imitate the layout of a similar table on another server.
So, I'd like my output to look like this:
+------+------+----------+----------+------+
| Col1 | Col2 | Col3 | Col4 | Col5 |
+------+------+----------+----------+------+
| AA | BB | CCCCCCCC | DDDDDDDD | EEEE |
+------+------+----------+----------+------+
Now, I have something that works, but it seems entirely inefficient to me and executing queries against this view is quite time consuming in my testing. I use a CTE and XML to break out the columns, but this requires things like escaping the ampersand, etc.
So, what I currently have is this:
WITH cte (ColA, ColB, Colc, etc.)
AS
(
SELECT
CONVERT(XML,'<Account><Attribute>'
+ REPLACE(REPLACE(MY_COLUMN,'&','&'),'-', '</Attribute><Attribute>')
+ '</Attribute></Account>') as ACCOUNT_VALUE
)
SELECT
ACCOUNT_VALUE.value('/Account[1]/Attribute[1]','varchar(2)') as Col1,
ACCOUNT_VALUE.value('/Account[1]/Attribute[2]','varchar(2)') as Col2,
ACCOUNT_VALUE.value('/Account[1]/Attribute[3]','varchar(8)') as Col3,
ACCOUNT_VALUE.value('/Account[1]/Attribute[4]','varchar(8)') as Col4,
ACCOUNT_VALUE.value('/Account[1]/Attribute[5]','varchar(4)') as Col5
FROM cte
And this returns the data fine, but takes exceptionally long. So, is there a better way to separate hyphenated data into columns within a T-SQL statement (preferably no functions, etc.)? This table has millions of rows that need to be broken out into separate columns.
I got this far via a few hours of Googling yesterday and haven't really found another option I've been able to make work.