我试图扩展我们的内置函数之一,它连接地址线1和2.我尝试将此逻辑扩展到地址线1,2,3和4.内置函数的示例如下所示。三条线后我的大脑停止了工作。如果你们能帮助我,我将不胜感激。谢谢
CREATE function [dbo].[UFN_CONCATENATEADDRESSLINES]
(
@ADDRESSLINE1 nvarchar(max),
@ADDRESSLINE2 nvarchar(max)
)
returns nvarchar(max)
as
begin
declare @ADDRESSBLOCK nvarchar(max);
set @ADDRESSBLOCK =
case when (@ADDRESSLINE1 is null and @ADDRESSLINE2 is null)
then null
when (@ADDRESSLINE1 is not null and @ADDRESSLINE2 is null)
then
case when len(ltrim(rtrim(@ADDRESSLINE1))) > 0
then @ADDRESSLINE1
else null end
when (@ADDRESSLINE1 is null and @ADDRESSLINE2 is not null)
then
case when len(ltrim(rtrim(@ADDRESSLINE2))) > 0
then @ADDRESSLINE2
else null end
else -- (@ADDRESSLINE1 is not null and @ADDRESSLINE2 is not null)
case when len(ltrim(rtrim(@ADDRESSLINE1))) > 0 and len(ltrim(rtrim(@ADDRESSLINE2))) = 0
then @ADDRESSLINE1
when len(ltrim(rtrim(@ADDRESSLINE1))) = 0 and len(ltrim(rtrim(@ADDRESSLINE2))) > 0
then @ADDRESSLINE2
else (@ADDRESSLINE1 + char(13) + char(10) + @ADDRESSLINE2) end
end;
return @ADDRESSBLOCK;
end
我为新扩展功能构建的Matrix动作如下所示。
Add1 |Add2 | Add3 |Add4 |Action
--------------------------------------------------------------------------------
Filled |Filled |Filled |Filled |Bring all columns as address block
Filled |Filled |Filled |NULL |Bring first 3 as address block
Filled |Filled |NULL |NULL |Bring first 2 as address block
Filled |NULL |NULL |NULL |Bring only 1 as address block
NULL |NULL |NULL |NULL |Mark it as null
NULL |NULL |NULL |Filled |Move 4 to 1
NULL |NULL |Filled |Filled |Move 3 and 4 to 1 and 2 respectively
NULL |Filled |Filled |Filled |Move 2 to 1, 3 to 2 and 4 to 3
Filled |Filled |NULL |Filled |Move 4 to 3
Filled |NULL |NULL |Filled |Move 4 to 2
Filled |NULL |Filled |Filled |Move 3 and 4 to 2 and 3
答案 0 :(得分:0)
我认为这个功能可以满足您的需求。它以统一的方式执行此操作,而不是遵循您对表中某些行的略微奇怪的规范:
create function dbo.CompressAddress (
@AddressLine1 nvarchar(max),
@AddressLine2 nvarchar(max),
@AddressLine3 nvarchar(max),
@AddressLine4 nvarchar(max)
)
returns nvarchar(max)
as
begin
return
NULLIF(COALESCE(CASE WHEN LEN(RTRIM(@AddressLine1))>0 THEN
LTRIM(RTRIM(@AddressLine1)) END + char(13) + char(10),'') +
COALESCE(CASE WHEN LEN(RTRIM(@AddressLine2))>0 THEN
LTRIM(RTRIM(@AddressLine2)) END + char(13) + char(10),'') +
COALESCE(CASE WHEN LEN(RTRIM(@AddressLine3))>0 THEN
LTRIM(RTRIM(@AddressLine3)) END + char(13) + char(10),'') +
COALESCE(CASE WHEN LEN(RTRIM(@AddressLine4))>0 THEN
LTRIM(RTRIM(@AddressLine4)) END,''),'')
end
go