我正在使用MS SQL Server。
我有一列名为first name
的数据,格式为ANNETTE W * LOW
我想创建另一个名为last name
的列,并将first name
之后的*
列中的所有数据放入此新列中。
first name
---------------
ANNETTE W * LOW
first name | last name
-----------+----------
ANNETTE W | LOW
答案 0 :(得分:2)
您可以使用CHARINDEX
和SUBSTRING
来完成
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
答案 1 :(得分:-1)
您在代码下面。
SELECT
SUBSTRING(Firstname,1,CHARINDEX('*',Firstname)-1) AS FName
, SUBSTRING(Firstname,CHARINDEX('*',Firstname)+1,LEN(Firstname)) AS LName
FROM Tablename T