I have the following SQL to format a US address into each line for a mailing address but it is rather ugly. Is there a better way to solve this problem or does it have to be this ugly? Also, the problem with this code is that it always ends up with an extra new line at the end.
declare #NL varchar(2);
set #NL = char(13) + char(10);
select
case when rtrim(coalesce(AttentionLine,'') ) != '' then rtrim(AttentionLine ) + #NL else '' end
+ case when rtrim(coalesce(Recipient,'') ) != '' then rtrim(Recipient ) + #NL else '' end
+ case when rtrim(coalesce(AddlAddrLine,'') ) != '' then rtrim(AddlAddrLine ) + #NL else '' end
+ case when rtrim(coalesce(DeliveryAddr,'') ) != '' then rtrim(DeliveryAddr ) + #NL else '' end
+ case when rtrim(coalesce(LastLine,'') ) != '' then rtrim(LastLine ) + #NL else '' end
+ case when rtrim(coalesce(Country,'') ) != '' then rtrim(Country ) + #NL else '' end
as FormattedMailingAddress
from Address
where Id = 1
If your Sql Server Settings are such that NULL + varchar returns NULL (SET CONCAT_NULL_YIELDS_NULL (Transact-SQL)), this can help.
DECLARE #Address TABLE(
ID INT,
AttentionLine VARCHAR(50),
Recipient VARCHAR(50),
AddlAddrLine VARCHAR(50),
DeliveryAddr VARCHAR(50),
LastLine VARCHAR(50),
Country VARCHAR(50)
)
declare #NL varchar(2);
set #NL = char(13) + char(10);
INSERT INTO #Address SELECT 1, NULL, '1', NULL, '2', NULL, '3'
select
case when rtrim(coalesce(AttentionLine,'') ) != '' then rtrim(AttentionLine ) + #NL else '' end
+ case when rtrim(coalesce(Recipient,'') ) != '' then rtrim(Recipient ) + #NL else '' end
+ case when rtrim(coalesce(AddlAddrLine,'') ) != '' then rtrim(AddlAddrLine ) + #NL else '' end
+ case when rtrim(coalesce(DeliveryAddr,'') ) != '' then rtrim(DeliveryAddr ) + #NL else '' end
+ case when rtrim(coalesce(LastLine,'') ) != '' then rtrim(LastLine ) + #NL else '' end
+ case when rtrim(coalesce(Country,'') ) != '' then rtrim(Country ) + #NL else '' end
as FormattedMailingAddress ,
RTRIM(coalesce(AttentionLine + #NL,'')) +
RTRIM(coalesce(Recipient + #NL,'')) +
RTRIM(coalesce(AddlAddrLine + #NL,'')) +
RTRIM(coalesce(DeliveryAddr + #NL,'')) +
RTRIM(coalesce(LastLine + #NL,'')) +
RTRIM(coalesce(Country + #NL,''))
from #Address
where Id = 1
I realize this is an old question, but there is a new solution to this problem: the CONCAT_WS() function, which is new for SQL Server 2017 (it's also available for Azure SQL Database).
SELECT CONCAT_WS (
CHAR(13) + CHAR(10), --Separator
NULLIF(AttentionLine, ''),
NULLIF(Recipient, ''),
NULLIF(AddlAddrLine, ''),
NULLIF(DeliveryAddr, ''),
NULLIF(LastLine, ''),
NULLIF(Country, '')
)
AS FormattedMailingAddress
FROM Address
WHERE Id = 1
NULL values are ignored by the function, which is why NULLIF is used with each argument/parameter in this example. (When the argument/parameter evaluates to NULL, the separator won't be added either). Here's a short blog post with some more details: New For SQL Server 2017: T-SQL Function CONCAT_WS
Related
What is wrong in this?
The error comes from this section;
AND ('''+#searchText+''' = '''' OR (ISNULL(CAST(t1.id as varchar(10)),'''') + '' '' +
ISNULL(CAST(FORMAT(t1.reading_date,#dateformat) as varchar(12)),'''')+'' '' +
ISNULL(t2.description,'''') + '' '' +
ISNULL(t3.equipment_no,'''') + '' '' +
ISNULL(t4.description,'''') + '' '' +
ISNULL(CAST(t1.actual_usage as nvarchar(16)),'''') + '' '' +
ISNULL(t5.uom_code,'''') + '' '' +
ISNULL(CAST(t1.actual_cost as nvarchar(16)),'''') + '' '' +
ISNULL(t6.currency_code,'''') + '' '' +
ISNULL(t1.comment,'''') + '' '' +
ISNULL(CAST(FORMAT(t1.actual_date,#dateformat) as varchar(12)),'''')) LIKE ''%'' '''+#searchText+''' ''%'')
The error:
Msg 102, Level 15, State 1, Line 59
Incorrect syntax near ''.
You can use CONCAT(string1, string2, ...., string_n) instead of doing it manually using + operator. Also, use COALESCE to return column value or empty string. This will simplify the query.
Sample for using CONCAT()
DECLARE #searchText AS VARCHAR(50) = 'SearchMe'
DECLARE #sqlQuery2 AS VARCHAR(5000)
DECLARE #Column1 AS VARCHAR(50) = 'TestValue1'
SET #sqlQuery2 = ' FROM Table
WHERE Column1 = ''' + #Column1 + '''
AND ('''+#searchText+''' = '''' OR (CONCAT(
ISNULL(CAST(t1.id as varchar(10)), '''')
, '' ''
, ISNULL(CAST(FORMAT(t1.reading_date,#dateformat) as varchar(12)), '''')
, '' ''
, ISNULL(t2.description, '''')
, '' ''
, ISNULL(t3.equipment_no, '''')
, '' ''
, ISNULL(t4.description, '''')
, '' ''
, ISNULL(CAST(t1.actual_usage as nvarchar(16)), '''')
, '' ''
, ISNULL(t5.uom_code, '''')
, '' ''
, ISNULL(CAST(t1.actual_cost as nvarchar(16)), '''')
, '' ''
, ISNULL(t6.currency_code, '''')
, '' ''
, ISNULL(t1.comment, '''')
, '' ''
, ISNULL(CAST(FORMAT(t1.actual_date,#dateformat) as varchar(12)), ''''))
)) LIKE ''% ' + #searchText + ' %''
)
ORDER BY someColumn '
select #sqlQuery2
Also noted that LIKE statement string in your code will return syntax error.
Replace the string
LIKE ''%'' ''' + #searchText + ''' ''%''
by this
LIKE ''% ' + #searchText + ' %''
I hope it will help.
I want to have the procedure which includes dynamic query and giving perfect result. But I want to use the procedure in another procedure.
When I write the query like
select procedurename from table name t1
it returns
procedure is not a recognized built-in function name.
Simply call testa from testb like:
EXEC testa #newId, #prod, #desc;
Make sure to get #id using:
SELECT #newId = ##SCOPE_IDENTITY
You should cteate a temporary table out of your procedure and insert the result of your first proc using INSERT..EXEC:
create #t (...);
insert #t(...) exec sp1;
At this point your second proc can use #t to select from it
Another solution can be turning your proc into multi-statement function but it's not the case since you use a dynamic code
i have a table named savedsearch which has few columns named username mobile lastloginbefore etc
Then i use this procedure for dynamic query
ALTER PROCEDURE [dbo].[usp_GetCouponStatusProcedure1] --26072,54
#UserID INT,
#SavedSearch VARCHAR(550)
AS
BEGIN
DECLARE #Email1 VARCHAR(50),
#Mobile1 VARCHAR(50),
#UserFilter1 VARCHAR(50),
#UserName1 VARCHAR(50),
#UserType1 VARCHAR(50),
#LastLoginBefore1 VARCHAR(50),
#LastLogin1 VARCHAR(50),
#LastPurchase1 VARCHAR(50)
SELECT #UserName1 = ss.UserName,
#Email1 = ss.EmailID,
#Mobile1 = ss.Mobile,
#UserFilter1 = ss.UserFilter,
#UserType1 = ss.UserType,
#LastLoginBefore1 = ss.LastLoginBefore,
#LastPurchase1 = ss.LastPurchase,
#LastLogin1 = ss.LastLogin
FROM SavedSearch AS ss
WHERE ss.ID = #SavedSearch
DECLARE #String NVARCHAR(1000) =
'SELECT SearchName into #Temp
FROM SavedSearch AS ss '
DECLARE #LastLogin VARCHAR(500),
#Email VARCHAR(500),
#Mobile VARCHAR(500),
#UserFilter VARCHAR(500),
#UserName VARCHAR(500),
#UserType VARCHAR(500),
#LastLoginBefore VARCHAR(500),
#LastPurchase VARCHAR(500),
#WhereClause VARCHAR(500),
#WhereClause1 VARCHAR(500),
#WhereClause2 VARCHAR(500),
#WhereClause3 VARCHAR(500),
#WhereClause4 VARCHAR(500),
#WhereClause5 VARCHAR(500),
#WhereClause6 VARCHAR(500),
#WhereClause7 VARCHAR(500),
#WhereClause8 VARCHAR(500)
SET #WhereClause = ' WHERE ss.ID = #SavedSearch1 AND ('
DECLARE #i INT
IF #LastLogin1 <> 0
BEGIN
SET #LastLogin =
' CROSS APPLY funcToGetNewUserLastLogin(ss.LastLogin) AS ftll '
SET #WhereClause1 = ' ftll.[User_ID] = #UserID1 '
END
IF #Email1 <> ''
BEGIN
SET #Email =
' CROSS APPLY funcToGetUserForGivenEmail(ss.EmailID) AS ftEm '
SET #WhereClause2 = ' ftEm.[User_ID] = #UserID1 '
END
IF #Mobile1 <> 0
BEGIN
SET #Mobile =
' CROSS APPLY funcToGetUserForGivenMobile(ss.Mobile) AS ftmo '
SET #WhereClause3 = ' ftmo.[User_ID] = #UserID1 '
END
IF #UserFilter1 <> ''
BEGIN
SET #UserFilter =
' CROSS APPLY funcToGetUserForGivenUserFilter(ss.UserFilter) AS ftUf '
SET #WhereClause4 = ' ftUf.[User_ID] = #UserID1 '
END
IF #UserName1 <> ''
BEGIN
SET #UserName =
' CROSS APPLY funcToGetUserForGivenUserName(ss.UserName) AS ftun '
SET #WhereClause5 = ' ftun.[User_ID] = #UserID1 '
END
IF #UserType1 <> ''
BEGIN
SET #UserType =
' CROSS APPLY funcToGetUserForGivenUserType(ss.UserType) AS ftut '
SET #WhereClause6 = ' ftut.[User_ID] = #UserID1 '
END
IF #LastLoginBefore1 <> 0
BEGIN
SET #LastLoginBefore =
' CROSS APPLY funcToGetUserLastLoginBefore(ss.LastLoginBefore) AS ftlb '
SET #WhereClause7 = ' ftlb.[User_ID] = #UserID1 '
END
IF #LastPurchase1 <> 0
BEGIN
SET #LastPurchase =
' CROSS APPLY funcToGetUserLastPurchased(ss.LastPurchase) AS ftpur '
SET #WhereClause8 = ' ftpur.[User_ID] = #UserID1 '
END
SET #String = #String + ISNULL(#Email, '') + ISNULL(#UserName, '') + ISNULL(#UserType, '')
+ ISNULL(#UserFilter, '') + ISNULL(#LastLogin, '')
+ ISNULL(#LastLoginBefore, '') + ISNULL(#LastPurchase, '') + ISNULL(#Mobile, '')
+ ISNULL(#WhereClause, '') + CASE
WHEN #WhereClause1 <> '' THEN CASE
WHEN
#WhereClause2
<
>
''
OR
#WhereClause3
<
>
''
OR
#WhereClause8
<
>
''
OR
#WhereClause7
<
>
''
OR
#WhereClause6
<
>
''
OR
#WhereClause5
<
>
''
OR
#WhereClause4
<
>
'' THEN
ISNULL(#WhereClause1, '')
+
' OR '
ELSE
ISNULL(#WhereClause1, '')
END
ELSE ''
END + CASE
WHEN #WhereClause2 <> '' THEN CASE
WHEN
#WhereClause3
<
>
''
OR
#WhereClause8
<
>
''
OR
#WhereClause7
<
>
''
OR
#WhereClause6
<
>
''
OR
#WhereClause5
<
>
''
OR
#WhereClause4
<
>
'' THEN
ISNULL(#WhereClause2, '')
+
' OR '
ELSE
ISNULL(#WhereClause2, '')
END
ELSE ''
END + CASE
WHEN #WhereClause3 <> '' THEN CASE
WHEN
#WhereClause8
<
>
''
OR
#WhereClause7
<
>
''
OR
#WhereClause6
<
>
''
OR
#WhereClause5
<
>
''
OR
#WhereClause4
<
>
'' THEN
ISNULL(#WhereClause3, '')
+
' OR '
ELSE
ISNULL(#WhereClause3, '')
END
ELSE ''
END + CASE
WHEN #WhereClause4 <
> '' THEN CASE
WHEN
#WhereClause8
<
>
''
OR
#WhereClause7
<
>
''
OR
#WhereClause6
<
>
''
OR
#WhereClause5
<
>
'' THEN
ISNULL(#WhereClause4, '')
+
' OR '
ELSE
ISNULL(#WhereClause4, '')
END
ELSE ''
END + CASE
WHEN #WhereClause5
<> '' THEN CASE
WHEN
#WhereClause8
<
>
''
OR
#WhereClause7
<
>
''
OR
#WhereClause6
<
>
'' THEN
ISNULL(#WhereClause5, '')
+
' OR '
ELSE
ISNULL(#WhereClause5, '')
END
ELSE ''
END + CASE
WHEN #WhereClause6
<>
'' THEN CASE
WHEN
#WhereClause8
<
>
''
OR
#WhereClause7
<
>
'' THEN
ISNULL(#WhereClause6, '')
+
' OR '
ELSE
ISNULL(#WhereClause6, '')
END
ELSE ''
END + CASE
WHEN
#WhereClause7
<
>
'' THEN CASE
WHEN
#WhereClause8
<
>
'' THEN
ISNULL(#WhereClause7, '')
+
' OR '
ELSE
ISNULL(#WhereClause7, '')
END
ELSE
''
END + CASE
WHEN
#WhereClause6
<
>
'' THEN
ISNULL(#WhereClause6, '')
ELSE
''
END
+ ' )'
DECLARE #ParmDefinition NVARCHAR(500) =
N'#UserID1 INT, #SavedSearch1 varchar(500),#ii int OUTPUT';
DECLARE #UserID1 INT,
#SavedSearch1 VARCHAR(500)
EXECUTE sp_executesql #String,
#ParmDefinition,
#UserID1 = #UserID,
#SavedSearch1 = #SavedSearch,
#ii = #i OUTPUT
DECLARE #rowcount INT
SET #rowcount = ##rowcount
SELECT --#SavedSearch AS savedsearchid,
#rowcount AS ReturnedValue
--PRINT #String
--SELECT #i
END
I've got this query below that drove me mad, would you be able to fix the code below so that the result will be like this : "123 Bridge St 2500" instead of " 123 Bridge St 2500" (extra whitespace at the beginning and in between St and 2500)?
declare #street varchar(20), #street2 varchar(20), #suburb varchar(20), #postcode varchar(4)
set #street = null
set #street2 = '123 Bridge St'
set #suburb = null
set #postcode = '2500'
select address = case #street when null then '' else #street + ' ' end
+case #street2 when null then '' else #street2 + ' ' end
+case #suburb when null then '' else #suburb + ' ' end
+case #postcode when null then '' else #postcode + ' ' end
-- Expected Result: '123 Bridge St 2500'
-- Actual Result: ' 123 Bridge St 2500'
Thanks!
Try
select case when #street is null then '' else #street + ' ' end
+case when #street2 is null then '' else #street2 + ' ' end
+case when #suburb is null then '' else #suburb + ' ' end
+case when #postcode is null then '' else #postcode + ' ' end
When you write case #street when null.. that's the same as when #street = null which doesn't work, so use is null instead.
Thanks for all your comments,
here's the solution that worked
select address = ltrim(rtrim(#street) + ' ') + ltrim(rtrim(#street2) + ' ') + ltrim(rtrim(#suburb) + ' ') + #postcode
Hey I am having a problem with a View I am trying to create I am trying to get the Full Address of a member be Displayed in correlation with the MemberID of my Member Table along with a few other fields in other tables but the FullAddress and MFullAddress are both coming up as NULL Values and I am not sure why hope someone can help. Below is the Code for my View.
SELECT dbo.Member.MemberID, dbo.Member.Title + ' ' + dbo.Member.Forename + ' ' + dbo.Member.Surname AS Fullname, dbo.GetMemberFullAddress(dbo.Member.MemberID) AS FullAddress,
dbo.GetMemberFullMailingAddress(dbo.Member.MemberID) AS MFullAddress, dbo.Lookup_ActionType.Description, dbo.Payment.Amount
FROM dbo.Payment RIGHT OUTER JOIN
dbo.Member ON dbo.Payment.PaymentID = dbo.Member.MemberID RIGHT OUTER JOIN
dbo.Action LEFT OUTER JOIN
dbo.Lookup_ActionType ON dbo.Action.ActionTypeID = dbo.Lookup_ActionType.ActionTypeID ON dbo.Member.MemberID = dbo.Action.MemberID
WHERE (dbo.Member.MemberID = dbo.Member.MemberID)
And here are Both of my Functions Called dbo.GetFullMemberAddress The Mfulladdress function is the same only different fields
USE [ICOM.Database]
GO
/****** Object: UserDefinedFunction [dbo].[GetMemberFullAddress] Script Date: 22/10/2014 11:53:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Richard Glass>
-- Create date: <22/10/2014>
-- Description: <Returns Full Address>
-- =============================================
ALTER FUNCTION [dbo].[GetMemberFullAddress]
-- Add the parameters for the function here
(#MemberID as integer)
RETURNS varchar(250)
AS
BEGIN
DECLARE #AddressLine as varchar(40)
DECLARE #FullAddress as varchar(250)
SET #FullAddress = (SELECT LTRIM(ISNULL(Title + ' ', '') + ForeName + ' ' + Surname) AS FullName FROM Member WHERE MemberID = #MemberID) + CHAR(10)
SET #FullAddress = #FullAddress + #AddressLine + CHAR(10)
SET #AddressLine = (SELECT Member.AddressLine1 FROM Member WHERE MemberID = #MemberID)
SET #FullAddress = #FullAddress + #AddressLine + CHAR(10)
SET #AddressLine = (SELECT AddressLine2 FROM Member WHERE MemberID = #MemberID)
IF #AddressLine <> ''
BEGIN
SET #FullAddress = #FullAddress + #AddressLine + CHAR(10)
END
SET #AddressLine = (SELECT AddressLine3 FROM Member WHERE MemberID = #MemberID)
IF #AddressLine <> ''
BEGIN
SET #FullAddress = #FullAddress + #AddressLine + CHAR(10)
END
SET #AddressLine = (SELECT Town FROM Member WHERE MemberID = #MemberID)
IF #AddressLine <> ''
BEGIN
SET #FullAddress = #FullAddress + #AddressLine + CHAR(10)
END
SET #AddressLine = (SELECT PostCode FROM Member WHERE MemberID = #MemberID)
SET #FullAddress = #FullAddress + #AddressLine
RETURN #FullAddress
END
AND
The problem is because concatenetating NULL with anything yields NULL by default. At the start of the function you have:
DECLARE #AddressLine as varchar(40)
DECLARE #FullAddress as varchar(250)
SET #FullAddress = (SELECT LTRIM(ISNULL(Title + ' ', '') + ForeName + ' ' + Surname) AS FullName FROM Member WHERE MemberID = #MemberID) + CHAR(10)
SET #FullAddress = #FullAddress + #AddressLine + CHAR(10)
And the problem line is:
SET #FullAddress = #FullAddress + #AddressLine + CHAR(10)
At this point #AddressLine is NULL, therefore you set #FullAddress to NULL.
You can get your full address though in a much less convoluted fashion, something like:
(LTRIM(ISNULL(Title + ' ', '') + ForeName + ' ' + Surname) + ',' +
CASE WHEN ISNULL(AddressLine1, '') = '' THEN '' ELSE AddressLine1 + ',' END +
CASE WHEN ISNULL(AddressLine2, '') = '' THEN '' ELSE AddressLine2 + ',' END +
CASE WHEN ISNULL(AddressLine3, '') = '' THEN '' ELSE AddressLine3 + ',' END +
CASE WHEN ISNULL(Town, '') = '' THEN '' ELSE Town + ',' END +
CASE WHEN ISNULL(PostCode, '') = '' THEN '' ELSE PostCode END
Although seemingly quite verbose, it does not require repeatedly querying the member table. You could then just add this as a computed column:
I would be inclined to add MemberAddress as a computed column to dbo.Member though, something like:
ALTER TABLE dbo.Member
ADD MemberAddress AS
(LTRIM(ISNULL(Title + ' ', '') + ForeName + ' ' + Surname) + ',' +
CASE WHEN ISNULL(AddressLine1, '') = '' THEN '' ELSE AddressLine1 + ',' END +
CASE WHEN ISNULL(AddressLine2, '') = '' THEN '' ELSE AddressLine2 + ',' END +
CASE WHEN ISNULL(AddressLine3, '') = '' THEN '' ELSE AddressLine3 + ',' END +
CASE WHEN ISNULL(Town, '') = '' THEN '' ELSE Town + ',' END +
CASE WHEN ISNULL(PostCode, '') = '' THEN '' ELSE PostCode END;
Would your stored proc be better if the code was just this?
DECLARE #FullAddress as varchar(250)
SELECT FullAddress = LTRIM(ISNULL(Title + ' ', '') + ForeName + ' ' + Surname)
+ CHAR(10)
+ ISNULL(Member.AddressLine1 + CHAR(10),'')
+ ISNULL(Member.AddressLine2 + CHAR(10),'')
+ ISNULL(Member.AddressLine3 + CHAR(10),'')
+ ISNULL(Member.Town + CHAR(10),'')
+ ISNULL(Member.PostCode + CHAR(10),'')
FROM Member
WHERE MemberID = #MemberID
RETURN #FullAddress
How can I format a Mailing Address so that I always push all non-null rows to the top? That is, I want to convert an address from the structure below to a mailing address.
Here is the structure:
[Line1] [varchar](50) NULL,
[Line2] [varchar](50) NULL,
[Line3] [varchar](50) NULL,
[City] [varchar](50) NULL,
[State] [varchar] (2) NULL,
[PostalCode] [varchar](50) NULL,
Here is some sample data:
Line1=
Line2=123 Some Address
Line3=
City=Royal Oak
State=MI
ZIP=45673-2312
Here is what the result should look like (4 distinct or separate fields should be returned):
MailAddress1=123 Some Address
MailAddress2=ROYAL OAK MI 45673-2312
MailAddress3=
MailAddress4=
I am using SQL Server 2005.
Someone wrote this logic in our company and it just seemed to complex (Note: this is not the whole SELECT statement):
,CASE
WHEN eai.Line1 IS NULL OR eai.Line1 = '' THEN
CASE
WHEN eai.Line2 IS NULL OR eai.Line2 = '' THEN
CASE
WHEN eai.Line3 IS NULL OR eai.Line3 = '' THEN ISNULL(LTRIM(RTRIM(eai.City)),'') + ' ' + ISNULL(LTRIM(RTRIM(eai.RegionCode)),'') + ' ' + ISNULL(LTRIM(RTRIM(eai.PostalCode)),'')
ELSE eai.Line3
END
ELSE eai.Line2
END
ELSE eai.Line1
END
,CASE
WHEN eai.Line1 IS NULL OR eai.Line1 = '' THEN
CASE
WHEN eai.Line3 IS NULL OR eai.Line3 = '' THEN ISNULL(LTRIM(RTRIM(eai.City)),'') + ' ' + ISNULL(LTRIM(RTRIM(eai.RegionCode)),'') + ' ' + ISNULL(LTRIM(RTRIM(eai.PostalCode)),'')
ELSE eai.Line3
END
ELSE
CASE
WHEN eai.Line2 IS NULL OR eai.Line2 = '' THEN
CASE
WHEN eai.Line3 IS NULL OR eai.Line3 = '' THEN ISNULL(LTRIM(RTRIM(eai.City)),'') + ' ' + ISNULL(LTRIM(RTRIM(eai.RegionCode)),'') + ' ' + ISNULL(LTRIM(RTRIM(eai.PostalCode)),'')
ELSE eai.Line3
END
ELSE eai.Line2
END
END
,CASE
WHEN eai.Line1 IS NULL OR eai.Line1 = '' THEN
CASE
WHEN eai.Line2 IS NULL OR eai.Line2 = '' THEN NULL
ELSE
CASE
WHEN eai.Line3 IS NULL OR eai.Line3 = '' THEN NULL
ELSE ISNULL(LTRIM(RTRIM(eai.City)),'') + ' ' + ISNULL(LTRIM(RTRIM(eai.RegionCode)),'') + ' ' + ISNULL(LTRIM(RTRIM(eai.PostalCode)),'')
END
END
ELSE
CASE
WHEN eai.Line2 IS NULL OR eai.Line2 = '' THEN
CASE
WHEN eai.Line3 IS NULL OR eai.Line3 = '' THEN NULL
ELSE ISNULL(LTRIM(RTRIM(eai.City)),'') + ' ' + ISNULL(LTRIM(RTRIM(eai.RegionCode)),'') + ' ' + ISNULL(LTRIM(RTRIM(eai.PostalCode)),'')
END
ELSE
CASE
WHEN eai.Line3 IS NULL OR eai.Line3 = '' THEN ISNULL(LTRIM(RTRIM(eai.City)),'') + ' ' + ISNULL(LTRIM(RTRIM(eai.RegionCode)),'') + ' ' + ISNULL(LTRIM(RTRIM(eai.PostalCode)),'')
ELSE eai.Line3
END
END
END
,CASE WHEN eai.Line2 IS NOT NULL AND eai.Line2 <> '' AND eai.Line3 IS NOT NULL AND eai.Line3 <> '' THEN eai.City + ' ' + eai.RegionCode + ' ' + eai.PostalCode ELSE NULL END
The way to do this is with an UNPIVOT. Here is the solution:
With AddrTable as (
Select AddrFld, MailAddr From (
Select Cast(ISNULL([Line1], '') as Varchar(102)) as [A1],
Cast(ISNULL([Line2], '') as Varchar(102)) as [A2],
Cast(ISNULL([Line3], '') as Varchar(102)) as [A3],
Cast(ISNULL(LTRIM(RTRIM(City)),'') + ' ' + ISNULL(LTRIM(RTRIM(RegionCode)),'') + ' ' + ISNULL(LTRIM(RTRIM(PostalCode)),'') as Varchar(102)) as A4
From TableName Where UniqueID=#UniqueID) p
Unpivot (MailAddr For AddrFld in ([A1], [A2], [A3], [A4])) as unpvt)
Select Row_Number() over (Order by (Case Len(MailAddr) When 0 then 1 else 0 end), AddrFld) as RN,
MailAddr From AddrTable
Order By RN
Here's the output:
Address1
Westby WI 55555
-empty line-
-empty line-
Note that I had to use "Varchar(102)" as the field length (unpivot requires that all fields be the same) because your City/Region/Postal can have up to 102 chars in total. Also, note that "#UniqueID" is the identifier for the record whose address you need. This returns four and always four rows containing the data you need for your address.
UPDATE: If you need to return this as a set of four columns rather than four rows, then just plop it into a view and then query the view with a Pivot. I've included the view here for completeness as I had to change the above just a bit when creating the view so the uniqueID field was included and no sort was done (the sort is now done in the query):
Create View AddressRows AS
With AddrTable as (
Select UniqueID, AddrFld, MailAddr From (
Select UniqueID,
Cast(ISNULL([Line1], '') as Varchar(102)) as [A1],
Cast(ISNULL([Line2], '') as Varchar(102)) as [A2],
Cast(ISNULL([Line3], '') as Varchar(102)) as [A3],
Cast(ISNULL(LTRIM(RTRIM(City)),'') + ' ' + ISNULL(LTRIM(RTRIM(RegionCode)),'') + ' ' + ISNULL(LTRIM(RTRIM(PostalCode)),'') as Varchar(102)) as A4
From TableName Where UniqueID=#UniqueID) p
Unpivot (MailAddr For AddrFld in ([A1], [A2], [A3], [A4])) as unpvt)
Select UniqueID,
Row_Number() over (Order by (Case Len(MailAddr) When 0 then 1 else 0 end), AddrFld) as RN,
MailAddr From AddrTable
And then, when you want to pull your matching "row" out, Pivot it back using this SQL (notice that I am querying again using UniqueID):
Select [Addr1], [Addr2], [Addr3], [Addr4] From (
Select Top 4 'Addr' + Cast(Row_Number() over (Order by RN) as Varchar(12)) as AddrCol, -- "Top 4" needed so we can sneak the "Order By" in
MailAddr
From AddressRows Where UniqueID=#UniqueID
) p PIVOT (Max([MailAddr]) for AddrCol in ([Addr1], [Addr2], [Addr3], [Addr4])
) as pvt
This returns:
Addr1 Addr2 Addr3 Addr4
-------------- ------------------ ------------- ------------------
Address1 Westby WI 54667
Here's a three-minutes-invested solution:
DECLARE #address TABLE (
[Line1] [varchar](50) NULL,
[Line2] [varchar](50) NULL,
[Line3] [varchar](50) NULL,
[City] [varchar](50) NULL,
[State] [varchar] (2) NULL,
[PostalCode] [varchar](50) NULL
)
INSERT INTO #address (
[Line1],
[Line2],
[Line3],
[City],
[State],
[PostalCode]
)
VALUES (
NULL,
'123 Some Address',
NULL,
'Royal Oak',
'MI',
'45673-2312'
)
SELECT * FROM #address
SELECT
ISNULL(Line1 + CHAR(13), '')
+ ISNULL(Line2 + CHAR(13), '')
+ ISNULL(Line3 + CHAR(13), '')
+ ISNULL(City + ' ', '')
+ ISNULL([State] + ' ', '')
+ ISNULL(PostalCode, '')
FROM #address
Result:
123 Some Address
Royal Oak MI 45673-2312
Fiddle with the control characters until you get the result you need.
SELECT
LTRIM(RTRIM(LINE1)) + LTRIM(RTRIM(LINE2)) + LTRIM(RTRIM(LINE3)) AS MailAddress1,
LTRIM(RTRIM(CITY)) + ' ' + LTRIM(RTRIM(STATE)) + ' ' + LTRIM(RTRIM(POSTALCODE)) AS MailAddress2
FROM MyTable