我创建了此函数,将投资者名称分为第一,第二和最后。但是我想添加一个条件,如果中间名没有空格,则在单独的列中显示数字0,如果中间没有空格,则显示1,该怎么办?
这是我已经创建的功能:
ALTER function [dbo].[saveinvestornames]()
returns @investorsname table ( investor_name nvarchar(300),first_name nvarchar(300), middle_name nvarchar(300),last_name nvarchar(300) )
as
begin
insert into @investorsname
select
investor_name,
SUBSTRING(investor_name, CHARINDEX(', ', investor_name) + 2, CASE WHEN CHARINDEX(' ', investor_name, CHARINDEX(', ', investor_name) + 2) = 0 THEN LEN(investor_name) + 1 ELSE CHARINDEX(' ', investor_name, CHARINDEX(', ', investor_name) + 2) END - CHARINDEX(', ', investor_name) - 2)as FirstName,
RTRIM(LTRIM(REPLACE(REPLACE(investor_name,SUBSTRING(investor_name , 1, CHARINDEX(' ', investor_name) -1),''),REVERSE( LEFT( REVERSE(investor_name), CHARINDEX(' ', REVERSE(investor_name))-1 ) ),'')))as MiddleName,
right(investor_name, CHARINDEX(' ', REVERSE(investor_name))) as LastName
from investornames;
return;
end;
答案 0 :(得分:1)
只需将您的程序更改为:
ALTER function [dbo].[saveinvestornames]()
returns @investorsname table ( investor_name nvarchar(300),first_name nvarchar(300), middle_name nvarchar(300),last_name nvarchar(300), middleNameSpace bit )
as
begin
insert into @investorsname
select first_name, middle_name, last_name,
case when len(middle_name) - len(replace(middle_name, ' ', '')) = 0 then 0 else 1 end
from (
select
investor_name,
SUBSTRING(investor_name, CHARINDEX(', ', investor_name) + 2, CASE WHEN CHARINDEX(' ', investor_name, CHARINDEX(', ', investor_name) + 2) = 0 THEN LEN(investor_name) + 1 ELSE CHARINDEX(' ', investor_name, CHARINDEX(', ', investor_name) + 2) END - CHARINDEX(', ', investor_name) - 2)as FirstName,
RTRIM(LTRIM(REPLACE(REPLACE(investor_name,SUBSTRING(investor_name , 1, CHARINDEX(' ', investor_name) -1),''),REVERSE( LEFT( REVERSE(investor_name), CHARINDEX(' ', REVERSE(investor_name))-1 ) ),'')))as MiddleName,
right(investor_name, CHARINDEX(' ', REVERSE(investor_name))) as LastName
from investornames;
) a
return;
end;
它只是通过在替换列之后比较此列的长度来检查middle_name
中有多少空格。