需要在现有表中创建一个新列并将数据从1列拆分到新列

时间:2018-08-31 03:00:18

标签: sql-server

我正在使用MS SQL Server。

我有一列名为first name的数据,格式为ANNETTE W * LOW

我想创建另一个名为last name的列,并将first name之后的*列中的所有数据放入此新列中。

输入

first name
---------------
ANNETTE W * LOW

所需的输出

first name | last name
-----------+----------
ANNETTE W  | LOW

2 个答案:

答案 0 :(得分:2)

您可以使用CHARINDEXSUBSTRING来完成

  • charIndex('*',firstName)-它为您提供字符*在firstName中的位置。在这种情况下,charIndex('*',firstName) = 11
  • substring(firstName,1,charIndex('*',firstName) -1)-正在从起始位置= 1直到/长度charIndex('*',firstName)-1 = 11-1 = 10的firstName中提取字符串的一部分
  • substring(firstName , charIndex('*',firstName) + 1 ,len(firstName) - (charIndex('*',firstName)))-从firstName提取一个字符串,其中起点charIndex('*',firstName) + 1 = 11 + 1 = 12且len(firstName) - (charIndex('*',firstName))) = 15-11 = 4
  • 因为表达式LOW中有一个空格字符,所以需要添加LTRIM =来消除它。

代码

create table Source
 (firstName varchar(50))    
insert into Source(firstName)
values('ANNETTE W * LOW')

select 
    substring(firstName,1,charIndex('*',firstName) -1) as  firstName
    , ltrim(substring(firstName, charIndex('*',firstName) + 1
            ,len(firstName) - (charIndex('*',firstName)))) as lastName
    ,charIndex('*',firstName) as positionChar
    ,len(firstName) as lengthString
from Source as S 

输出:

firstName   lastName    positionChar    lengthString
ANNETTE W   LOW         11               15

ALTER TABLE Source
   ADD lastName varchar(50) null

UPDATE Source
  SET lastName = ltrim(substring(firstName, charIndex('*',firstName) + 1
                      ,len(firstName) - (charIndex('*',firstName))))
       ,firstName = substring(firstName,1,charIndex('*',firstName) -1)

SELECT * FROM Source

输出

firstName   lastName
ANNETTE W   LOW

dbfiddle

答案 1 :(得分:-1)

您在代码下面。

SELECT   
SUBSTRING(Firstname,1,CHARINDEX('*',Firstname)-1) AS FName
, SUBSTRING(Firstname,CHARINDEX('*',Firstname)+1,LEN(Firstname)) AS LName
FROM Tablename T