I have a table with a column that has multiple values stored in one column I want to query that data to a file and separate the values.
Example: This column (SHIFT_LENGTHS) has values stored as a concatenate of each day of the week with "#" as a separator which represents seconds for day of the week.
SELECT
NAME
,SHIFT_LENGTHS
FROM SHIFTGUARANTEE
ORDER BY NAME
SQL Results
NAME ,SHIFT_LENGTHS
Shift1,#14400#14400#14400#14400#14400#14400#14400#
I want to query the data and present it in a file this way:
NAME ,Mon ,Tue ,Wed ,Thu ,Fri ,Sat ,Sun
Shift1,14400,14400,14400,14400,14400,14400,14400
If the format of the string is fixed as it seems to be you could just parse it using the substring function:
SELECT
NAME
,SUBSTRING(SHIFT_LENGTHS, 2, 5) mon
,SUBSTRING(SHIFT_LENGTHS, 8, 5) tue
,SUBSTRING(SHIFT_LENGTHS, 14, 5) wed
,SUBSTRING(SHIFT_LENGTHS, 20, 5) thu
,SUBSTRING(SHIFT_LENGTHS, 26, 5) fri
,SUBSTRING(SHIFT_LENGTHS, 32, 5) sat
,SUBSTRING(SHIFT_LENGTHS, 38, 5) sun
FROM SHIFTGUARANTEE
ORDER BY NAME
If the format isn't fixed you can use the charindex function to get the indexes of the separators, or a custom CLR regex function.
There's also a good solution using cross apply in the answers to another question: How to split a comma-separated value to columns
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.