我的数据库中有一个列,用于存储标题,名字和姓氏。但是此列中的数据有时不干净,客户的标题缺失或为空,其他时间名称不可用,有些时间,姓氏无效。现在,我想将列分离或拆分为三个 - Title,FirstName,LastName,记住我必须检查空值或空数据。如何清除此数据以便出现以下错误:
Msg 536, Level 16, State 2, Line 1
Invalid length parameter passed to the RIGHT function.
或
Msg 537, Level 16, State 2, Line 1
Invalid length parameter passed to the LEFT or SUBSTRING function.
未退回。
我写了这样一个剧本,但还不够好。
SELECT FullName
, LEFT(FullName, ISNULL(NULLIF(CHARINDEX(' ', FullName) - 1, -1), LEN(FullName))) AS Title
, RIGHT(Salute, LEN(Salute) - CHARINDEX(' ', FullName, 1)) FirstName
, SUBSTRING(FullName, 1, CHARINDEX(' ', FullName, 19) - 1) LastName
FROM Details
如果我们有标题和名称,我们应该分成Title,FirstName。如果没有标题,我们会将其视为FirstName和LastName 谢谢。
答案 0 :(得分:1)
不是我最好的工作,但是:
鉴于评论中确定的规则,http://sqlfiddle.com/#!3/f87e8/18/0似乎有效。如果规则发生变化,应该在案例中移动现有代码以满足需求。
Select FullName,
CASE len(fullname) - len(replace(fullName,' ',''))
WHEN 2 then
LEFT(FULLNAME,charIndex(' ',FULLNAME))
WHEN 1 then
''
when 0 then
''
end as Title,
CASE len(fullname) - len(replace(fullName,' ',''))
WHEN 2 then
REPLACE(REPLACE(FULLNAME,LEFT(FULLNAME,charIndex(' ',FULLNAME)),''),REVERSE(LEFT(REVERSE(FULLNAME),CHARINDEX(' ', REVERSE(FullName)))),'')
WHEN 1 then
LEFT(FULLNAME,CHARINDEX(' ', FullName))
when 0 then
''
end as First,
CASE len(fullname) - len(replace(fullName,' ',''))
WHEN 2 then
REVERSE(LEFT(REVERSE(FULLNAME),CHARINDEX(' ', REVERSE(FullName))))
When 1 then
REVERSE(LEFT(REVERSE(FULLNAME),CHARINDEX(' ', REVERSE(FullName))))
WHEN 0 then
FullName
end as LAST
from foo
答案 1 :(得分:0)
仔细看看这个
RIGHT(Salute, LEN(Salute) - CHARINDEX(' ', FullName, 1)) FirstName
你能看到
CHARINDEX('',FullName,1)
可能超出Salute的范围
set nocount on;
declare @fullname char(200) = 'jonnywalker whiskey ';
declare @left int;
set @left = (select ISNULL(NULLIF(CHARINDEX(' ', @fullname) - 1, -1), LEN(@fullname)));
select @left;
select LEFT(@fullname, @left) AS Title
declare @salute char(200) = 'salute ';
declare @right int;
set @right = (select (LEN(@salute) - CHARINDEX(' ', @fullname, 1)));
select @right;
select RIGHT(@salute, @right) FirstName;