Just a day ago, we faced situation where one column in database contained two values which were separated by comma. We wanted to separate this two values in their own columns. It was interesting that value of the column was variable and something dynamic needed to be written.
Following is quick script which separates one column into two columns. The separate between two values in comma.
CREATE TABLE EMP_Demo (EMP_PAY VARCHAR(20), EMP_NAME VARCHAR(20), PAY_SCALE VARCHAR(20)); INSERT INTO EMP_DEMO(EMP_PAY) VALUES ('ALPESH,7009') INSERT INTO EMP_DEMO(EMP_PAY) VALUES ('KRUTI,9909') INSERT INTO EMP_DEMO(EMP_PAY) VALUES ('TANMAY,16000.7') INSERT INTO EMP_DEMO(EMP_PAY) VALUES ('NESHA,6060.8') INSERT INTO EMP_DEMO(EMP_PAY) VALUES ('DEVANG,14000') UPDATE EMP_Demo SET EMP_NAME = LEFT(EMP_PAY,CHARINDEX(',',EMP_PAY)-1) UPDATE EMP_Demo SET PAY_SCALE = RIGHT(EMP_PAY,LEN(EMP_PAY)-CHARINDEX(',',EMP_PAY)) SELECT * FROM EMP_Demo DROP TABLE EMP_Demo GO
Reference : Pinal Dave (http://www.SQLAuthority.com)







Great job, i am learning the sql server and a big fan of the person who are doing good job in the programming field
is there any way that able to do this?
i mean within the select statement.
It is good…
here CHARINDEX is just counting the position of the field. And thus creating the whole formula to provide the solution..
Good job Pinal
Hi,
good demo of CHARINDEX.
I want to add a column ‘DEPT’ after ‘EMP_NAME’ column before ‘PAY_SCALE’ in EMP_Demo table.
I want to add it using SQL statement in 2005.
how to do it?
Thanks a lot in advance.