SQL classic code-split column Value

Source: Internet
Author: User
Original: zhujian
Adapted from: AI xinjue Luo. Lu Hua (flowers bloom in ice and snow forests in the past 18 years)-12-16 Guangdong and Shenzhen

Table tb:
Id value
----------------------
1 aa, bb
2 aaa, bbb, ccc
To split the value column by id, the results are as follows:
Id value
-------------------
1 aa
1 bb
2 aaa
2 bbb
2 ccc

1. Old solution (SQL server 2000)
Select top 8000 id = IDENTITY (int, 1, 1) INTO # FROM syscolumns a, syscolumns B

Select. id, SUBSTRING (. [values], B. id, CHARINDEX (',',. [values] + ',', B. id)-B. id)
FROM tb A, # B
Where substring (',' + A. [values], B. id, 1) = ','

Drop table #

2. New Solution (SQL server 2005)

Create table tb (id int, value varchar (30 ))
Insert into tb values (1, 'aa, BB ')
Insert into tb values (2, 'aaa, bbb, ccc ')
Go
Select a. id, B. value
FROM (
SELECT id, [value] = CONVERT (xml, '<root> <v>' + REPLACE ([value], '</v> <v> ') + '</v> </root>') FROM tb
)
Outer apply (
SELECT value = N. v. value ('.', 'varchar (100) ') from a. [value]. nodes ('/root/V') N (v)
) B

Drop table tb

/*
Id value
-----------------------------------------
1 aa
1 bb
2 aaa
2 bbb
2 ccc

(5 rows affected)
*/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.