How to split one column into two columns in SQL Server

前端 未结 4 1877
我寻月下人不归
我寻月下人不归 2020-12-06 06:29

I have small question about SQL Server, please tell me how to solve this issue

Table: emp

   id    name
  ---------------
   1    abc_ra         


        
4条回答
  •  旧巷少年郎
    2020-12-06 06:43

    You miss the case where there's no underscore in the string, which causes the error. Instead, try:

    select
        case CHARINDEX('_', name) when 0 then name
            else SUBSTRING(name, 1, CHARINDEX('_', name) - 1) end firstName,
    
        case CHARINDEX('_', name) when 0 then name
            else SUBSTRING(name, CHARINDEX('_', name) + 1, LEN(name)) end lastname 
    from emp
    

    I assume in the case of a single word, you want to show them as both the first name and last name. You can change that value to whatever you prefer.

提交回复
热议问题