如何将字段中的文本拆分为新表 [英] How to split text in a field into a new table
问题描述
您好b $ b
我目前在我的数据库中有一个名为contactName的栏目
此字段将联系人名称和姓氏保存在一列中
我想将contactName拆分为两列(FirstName,LastName)。
名称和姓氏之间有一个空格,例如John Smith
我该怎么做?
尝试这个
声明 @ name varchar ( 50 )
set @ name = ' john smith'
select substring( @ name , 1 ,charindex( ' ', @ name , 1 ))fname,substring( @ name ,charindex(' ', @ name , 1 )+ 1,len( @名称跨度>) -charindex(' ', @ name , 1 )+ 1)lname
而不是@name变量使用你的专栏有姓氏姓氏
喜欢这个
select substring(contactname,1,charindex('',contactname,1))fname ,substring(contactname,charindex('',contactname,1)+ 1,len(contactname)-charindex('',contactname,1)+1)lname
试试这段代码。将@t替换为您的tablename,将Name替换为您的字段名称。
选择 SUBSTRING(name, 1 ,pos),SUBSTRING(name,pos + 1,LEN(name)-pos)
From (
选择 CHARINDEX(' ,name) as pos,name from @ t )p;
SELECT SUBSTRING(contactname,1,CHARINDEX('',contactname,1) )fname,SUBSTRING(contactname,CHARINDEX('',contactname,1)+ 1,LEN(contactname)-CHARINDEX('',contactname,1)+1)lname
FROM table_name
Hi
I currently have a column in my database called contactName
This fields holds the contacts Name and surname in one column
I would like to split the contactName into two columns (FirstName,LastName).
There is a space in between the name and surname e.g. John Smith
How can i do this?
TRY THIS
declare @name varchar(50) set @name='john smith' select substring(@name,1,charindex(' ',@name,1))fname,substring(@name,charindex(' ',@name,1)+1,len(@name)-charindex(' ',@name,1)+1)lname
Instead of @name variable use your column which has firstname lastname
like this
select substring(contactname,1,charindex(' ',contactname,1))fname,substring(contactname,charindex(' ',contactname,1)+1,len(contactname)-charindex(' ',contactname,1)+1)lname
Try this code. Replace @t with your tablename and Name with your field name.
select SUBSTRING(name,1,pos),SUBSTRING(name,pos+1,LEN(name)-pos) From( select CHARINDEX(' ',name) as pos,name from @t) p;
SELECT SUBSTRING(contactname,1,CHARINDEX(' ',contactname,1))fname,SUBSTRING(contactname,CHARINDEX(' ',contactname,1)+1,LEN(contactname)-CHARINDEX(' ',contactname,1)+1)lname
FROM table_name
这篇关于如何将字段中的文本拆分为新表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!