[英]splitting string from one column and extracting one part of string to another column in sql
I use sql server 2008 r2. 我使用SQL Server 2008 R2。 The problem started when one person entered data into the datebase in two different formats.
当一个人以两种不同的格式将数据输入日期数据库时,问题就开始了。
The table is: ( as u can notice there are FName
and LName
in column 'Title' but it should be in FName
and LName
columns respectively. 该表是:(正如您所注意到的,在“标题”列中有
FName
和LName
,但它们应该分别在FName
和LName
列中。
Title FirstName LastName
-------------------------------------------------------------------
Prasident Ena Enic null null *(not ok)*
Prasident Hana Hanic *(ok)*
Prasident Jack Johnson null null *(wrong)*
So I splitted string in Title into 3 parts ( Title
, SFirstName
and SLastName
) using the code below. 所以我使用下面的代码将
Title
字符串分为3个部分( Title
, SFirstName
和SLastName
)。
ltrim(SUBSTRING (title ,CHARINDEX(' ', title)+1,
charindex(' ',title+' ',charindex(' ',title)+1)-charindex(' ',title)-1)),
ltrim(substring(title, charindex(' ',title,charindex(' ',title)+1), len(title)))
and I got this type od table. 我得到了这种类型的od表。
SplittedTitle SplittedFirstName SplittedLastName FirstName LastName
-------------------------------------------------------------------------------
Prasident Ena Enic null null
Prasident Prasident Prasident Hana Hanic
Prasident Jack Johnson null null
Now I have problem with nulls in FirstName
and LastName
. 现在我在
FirstName
和LastName
null问题。 How can I transfer right data ( from SplittedFirstName and SplittedLastName) instead of nulls. 如何传输正确的数据(从SplittedFirstName和SplittedLastName)而不是null。 I hope anyone got the point what my problem is.
我希望任何人都明白我的问题所在。
Anyone have any idea? 有人知道吗 Which function should I use and how?
我应该使用哪个功能以及如何使用?
I think you want an update. 我想你要更新。 You can do this with an updatable CTE:
您可以使用可更新的CTE进行此操作:
with toupdate as (
<your query here>
)
update toupdate
set FirstName = SplittedFirstName,
LastName = SplittedLastName
where FirstName is null and LastName is null;
All you need to do now is,to run a update on that resultant table 您现在要做的就是在结果表上运行更新
UPDATE tablename
SET
FirstName = case when SplittedTitle <> SplittedFirstName
then SplittedFirstName end,
LastName = case when SplittedTitle <> SplittedLastName
then SplittedLastName end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.