SQL Server分开:FirstName,MiddleName和LastName

时间:2014-12-22 11:36:17

标签: mysql sql split

美好的一天! 我得到了一个" Varchar"这是客户端的全名,需要拆分这个" varchar"为:

  • " FirstName MidleName MiddleNameTwo LastName"

  • 需要输入" FirstName"在" Col1"

  • 需要输入" MiddleName,MiddleNameTwo in" col2"

  • 需要输入" LastName" in" Col3"

感谢您的帮助!

3 个答案:

答案 0 :(得分:0)

您应该使用子查询执行此任务

 INSERT INTO names(firstname, middlename, lastname)
 SELECT substringfunctionofyours(name), substringfunctionofyours(name), 
 substringfunctionofyours(name) FROM namefield

请记住,这只是一个虚拟查询,如果您像这样使用它将无效

答案 1 :(得分:0)

您可以将输入法更改为4个单独的字段吗?

如果你不能,那么在字符串的不同部分之间实现特定的分隔符? 在使用2个单词构建姓氏的情况下,如果分隔符是[空格]或任何其他字符,例如' - ',则没有确定性的方法来处理字符串。或者'这在名称中很常见。

使用像' |' :

Declare @FullName varchar(100) = 'FirstName|MidleName|MiddleNameTwo|LastName'
Print 'FirstName = ' + Substring(@FullName,1,charindex('|',@FullName)-1)
SELECT @FullName = Substring(@FullName,charindex('|',@FullName)+1,len(@fullName))
Print 'MiddleName1 = ' + Substring(@FullName,1,charindex('|',@FullName)-1)
SELECT @FullName = Substring(@FullName,charindex('|',@FullName)+1,len(@fullName))
Print 'MiddleName2 = ' + Substring(@FullName,1,charindex('|',@FullName)-1)
SELECT @FullName = Substring(@FullName,charindex('|',@FullName)+1,len(@fullName))
Print 'LastName = ' + @FullName

如果您没有其中一个部件,只要您保持结构,这也会有效。

Declare @FullName varchar(100) = 'FirstName|MidleName||LastName'
Print 'FirstName = ' + Substring(@FullName,1,charindex('|',@FullName)-1)
SELECT @FullName = Substring(@FullName,charindex('|',@FullName)+1,len(@fullName))
Print 'MiddleName1 = ' + Substring(@FullName,1,charindex('|',@FullName)-1)
SELECT @FullName = Substring(@FullName,charindex('|',@FullName)+1,len(@fullName))
Print 'MiddleName2 = ' + Substring(@FullName,1,charindex('|',@FullName)-1)
SELECT @FullName = Substring(@FullName,charindex('|',@FullName)+1,len(@fullName))
Print 'LastName = ' + @FullName

答案 2 :(得分:0)

假设您有一个像"ABC DEF GHI"

这样的名字

现在您需要First NameMiddle Namelast Name来自此字符串。

我们走了

 Select 
 Substring(Cast('ABC DEF GHI' as nvarchar),0,charindex(' ',Cast('ABC DEF GHI' as nvarchar))) as Col1,
 Substring(Cast('ABC DEF GHI' as nvarchar),charindex(' ',Cast('ABC DEF GHI' as nvarchar)),4)as Col2,
 Substring(Cast('ABC DEF GHI' as nvarchar),8,charindex(' ',Cast('ABC DEF GHI' as nvarchar)))as Col3

注意: This is MSSQL SERVER Query and Substring Function is Built in in MSSQL SERVER