SQL Server 2012 ORDER BY works differently? - sql

I have used the following code in SQL Server 2005 for years and recently upgraded to SQL Server 2012 and it has seemingly broken the ORDER BY clause. The code is supposed to display like so:
A
A1
B
B1
B2
B3
C
But is grouping all the lines of the same type together. Any ideas why?
DECLARE #PeriodStart DATETIME
DECLARE #PeriodEnd DATETIME
SELECT #PeriodEnd = Getdate(),
#PeriodStart = Dateadd(hour, -96, Getdate());
WITH outpq
AS (SELECT 1 AS grpOrd,
Cast(NULL AS VARCHAR(255)) AS posInGrp,
'A' AS Ord,
casenumberkey,
'A|' + clientskey + '|'
+ Cast(brtnumber AS VARCHAR(11)) + '|'
+ Isnull(Replace(CONVERT(CHAR(10), coverdate, 101), '/', ''), ''
)
+ '|'
+ Isnull(Replace(CONVERT(CHAR(10), coverdate, 101), '/', ''), ''
)
+ '|' + Isnull(parcelnumber, '') + '|'
+ Isnull(assessedbeg, '') + '|'
+ Isnull(assesseddim, '') + '|'
+ Isnull(abbrlegal, '') + '|'
+ Isnull(waterfrom, '') + '|'
+ Isnull(waterto, '') + '|'
+ Isnull(Cast(wateropen AS VARCHAR(50)), '')
+ '|' + Isnull(taxfrom, '') + '|' + Isnull(taxto, '')
+ '|'
+ Isnull(Cast(taxopen AS VARCHAR(50)), '') AS Extract
FROM newcitycollection.dbo.propertyinformation
WHERE datefinished BETWEEN #PeriodStart AND #PeriodEnd
AND clientkey = 2
UNION ALL
SELECT 1 AS grpOrd,
NULL AS posInGrp,
'A1',
A.casenumberkey,
'A1|' + '|' + '|' + B.liennumber + '|'
+ Isnull(Cast(B.lienamt AS VARCHAR(50)), '')
+ '|' + Isnull(Replace(liendate, '/', ''), '')
+ '|' + Isnull(B.lienreason, '') AS Extract
FROM newcitycollection.dbo.propertyinformation A
JOIN newcitycollection.dbo.muniliens B
ON B.casenumberkey = A.casenumberkey
WHERE A.datefinished BETWEEN #PeriodStart AND #PeriodEnd
AND clientkey = 2
UNION ALL
SELECT 2 AS grpOrd,
Cast(C.interestskey AS VARCHAR(11)) AS posInGrp,
'B',
A.casenumberkey,
'B|' + '|' + Isnull(C.first, '') + '|'
+ Isnull(C.middle, '') + '|' + Isnull(C.last, '')
+ '|' + Isnull(C.alias, '') + '|'
+ Isnull(C.comname, '') + '|'
+ Isnull(C.docrel, '') + '|'
+ Cast(C.interestskey AS VARCHAR(11)) AS Extract
FROM newcitycollection.dbo.propertyinformation A
JOIN newcitycollection.dbo.interests C
ON C.casenumberkey = A.casenumberkey
WHERE A.datefinished BETWEEN #PeriodStart AND #PeriodEnd
AND clientkey = 2
UNION ALL
SELECT 2 AS grpOrd,
Cast(C.interestskey AS VARCHAR(11)) AS posInGrp,
'B1',
A.casenumberkey,
'B1|' + Isnull(fulladd, '') + '|'
+ Isnull(D.city, '') + '|' + Isnull(D.state, '')
+ '|' + Isnull(D.zip, '') AS Extract
FROM newcitycollection.dbo.propertyinformation A
JOIN newcitycollection.dbo.interests C
ON C.casenumberkey = A.casenumberkey
JOIN newcitycollection.dbo.interestadd D
ON D.casenumberkey = A.casenumberkey
AND D.interestskey = C.interestskey
WHERE A.datefinished BETWEEN #PeriodStart AND #PeriodEnd
AND clientkey = 2
UNION ALL
SELECT 2 AS grpOrd,
Cast(C.interestskey AS VARCHAR(11)) AS posInGrp,
'B2',
A.casenumberkey,
'B2|' + '|' + Isnull(E.suitnumber, '') + '|'
+ Cast(E.bdate AS VARCHAR(11)) + '|'
+ Isnull(E.chapter, '') + '|' + Isnull(E.vs, '') AS Extract
FROM newcitycollection.dbo.propertyinformation A
JOIN newcitycollection.dbo.interests C
ON C.casenumberkey = A.casenumberkey
JOIN newcitycollection.dbo.banks E
ON E.casenumberkey = A.casenumberkey
AND E.interestskey = C.interestskey
WHERE A.datefinished BETWEEN #PeriodStart AND #PeriodEnd
AND clientkey = 2
UNION ALL
SELECT 3 AS grpOrd3,
NULL AS posInGrp,
'B3',
A.casenumberkey,
'B3|' + '|' + F.doctype + '|'
+ Isnull(Cast(F.docamt AS VARCHAR(50)), '')
+ '|'
+ Isnull(Replace(CONVERT(CHAR(10), docdate, 101), '/', ''), '')
+ '|'
+ Isnull(Replace(CONVERT(CHAR(10), recdate, 101), '/', ''), '')
+ '|' + Isnull(F.docid, '') + '|'
+ Isnull(F.grantee, '') + '|'
+ Isnull(F.grantor, '')
+ Cast(F.docidkey AS VARCHAR(11)) AS Extract
FROM newcitycollection.dbo.propertyinformation A
JOIN newcitycollection.dbo.documents F
ON F.casenumberkey = A.casenumberkey
WHERE A.datefinished BETWEEN #PeriodStart AND #PeriodEnd
AND clientkey = 2
UNION ALL
SELECT 4
AS grpOrd
,
NULL
AS posInGrp,
'C',
A.casenumberkey,
'C|' + Isnull(J.ctype, '') + '|'
+ Isnull(J.plaintiffname, '') + '|'
+ Isnull(J.plaintiffadd1, '') + '|'
+ Isnull(J.plaintiffcity, '') + '|'
+ Isnull(J.plaintiffstate, '') + '|'
+ Isnull(J.plaintiffzip, '') + '|' + '|'
+ Isnull(J.defendantname, '') + '|'
+ Isnull(J.defendantadd1, '') + '|'
+ Isnull(J.defcity, '') + '|'
+ Isnull(J.defstate, '') + '|'
+ Isnull(J.defzip, '') + '|' + '|'
+ Isnull(J.court, '') + '|' + Isnull(J.caseid, '')
+ '|' + Isnull(J.jamt, '') + '|'
+ Isnull(Replace(CONVERT(VARCHAR(10), jdate, 101), '/', ''), '')
+ '|'
+ Isnull(Replace(CONVERT(VARCHAR(10), reviveddate, 101), '/', ''
), ''
)
AS
Extract
FROM newcitycollection.dbo.propertyinformation A
JOIN acme.new_judgment_system.dbo.selected_compiled_clean J
ON J.casenumber = A.casenumberkey
WHERE A.datefinished BETWEEN #PeriodStart AND #PeriodEnd
AND clientkey = 2
AND J.plaintiffname NOT IN (SELECT plaintiff
FROM
newcitycollection.dbo.excluded_plaintiffs))
--Extract data set into a table -- dump table in .txt with current date as part of name then delete that table
SELECT extract
INTO datadump
FROM outpq
ORDER BY casenumberkey,
grpord,
posingrp,
ord
DECLARE #FileName VARCHAR(50),
#bcpCommand VARCHAR(2000)
SET #FileName = Replace('D:\LDExport\Argosy_import_'
+ CONVERT(CHAR(8), Getdate(), 1) + '_0001.txt', '/', '')
SET #bcpCommand = 'bcp "SELECT Extract FROM datadump" QUERYOUT "'
SET #bcpCommand = #bcpCommand + #FileName
+ '" -U sa -P $%^&*() -T -c'
EXEC master..Xp_cmdshell
#bcpCommand
DROP TABLE datadump

Your final query...
SELECT Extract FROM datadump
...doesn't have an ORDER BY. What do you expect?
Add an ORDER BY there. What you ordered by when you inserted has no bearing on future queries.

Related

LEFT JOIN question - Pervasive SQL - combining multiple records from one table into a single column

I am having some trouble with getting data into a column from a combination of two tables.
I'm using pervasive SQL and don't have access to pivot tables. I did a left join and tried union but am not getting the results I want.
I have a primary table - table A - That for a given contract has 10 summary 'colors'.
I am using a select statement and a case clause to string the 10 unique colors together with commas to properly determine the number of commas I am checking for values in those color fields.
This works well - I get a single row with all of the colors listed (10 fields into 1)
Table B contains records for the same contract and can have almost up to 2000 colors (detail colors).
If table B has colors then Table A doesn't.
Is there a way to select all of the colors in Table B into a single row and column and show all of the other column data in Table A?
What I want :
Contract +---------+ PHONENO +----------+ Color +------+------+
TEST 555-555-5555 BLUE,RED,GREEN,YELLOW
Instead of what I'm currently getting:
Contract+---------+ PHONENO +----------+ Color +------+------+
TEST 555-555-5555 BLUE
TEST 555-555-5555 RED
TEST 555-555-5555 GREEN
TEST 555-555-5555 YELLOW
SELECT TableA.ContractNo AS Contract,
TableA.PhoneNo,
CASE
WHEN TableA.Color10 <> '' then (TableA.Color1 + ',' + TableA.Color2 + ',' + TableA.Color3 + ',' + TableA.Color4 + ',' + TableA.Color5 + ',' + TableA.Color6 + ',' + TableA.Color7 + ',' + TableA.Color8 + ',' + TableA.Color9 + ',' + TableA.Color10)
WHEN TableA.Color9 <> '' then (TableA.Color1 + ',' + TableA.Color2 + ',' + TableA.Color3 + ',' + TableA.Color4 + ',' + TableA.Color5 + ',' + TableA.Color6 + ',' + TableA.Color7 + ',' + TableA.Color8 + ',' + TableA.Color9)
WHEN TableA.Color8 <> '' then (TableA.Color1 + ',' + TableA.Color2 + ',' + TableA.Color3 + ',' + TableA.Color4 + ',' + TableA.Color5 + ',' + TableA.Color6 + ',' + TableA.Color7 + ',' + TableA.Color8)
WHEN TableA.Color7 <> '' then (TableA.Color1 + ',' + TableA.Color2 + ',' + TableA.Color3 + ',' + TableA.Color4 + ',' + TableA.Color5 + ',' + TableA.Color6 + ',' + TableA.Color7)
WHEN TableA.Color6 <> '' then (TableA.Color1 + ',' + TableA.Color2 + ',' + TableA.Color3 + ',' + TableA.Color4 + ',' + TableA.Color5 + ',' + TableA.Color6)
WHEN TableA.Color5 <> '' then (TableA.Color1 + ',' + TableA.Color2 + ',' + TableA.Color3 + ',' + TableA.Color4 + ',' + TableA.Color5)
WHEN TableA.Color4 <> '' then (TableA.Color1 + ',' + TableA.Color2 + ',' + TableA.Color3 + ',' + TableA.Color4)
WHEN TableA.Color3 <> '' then (TableA.Color1 + ',' + TableA.Color2 + ',' + TableA.Color3)
WHEN TableA.Color2 <> '' then (TableA.Color1 + ',' + TableA.Color2)
WHEN TableA.Color1 <> '' then (TableA.Color1)
WHEN TableB.Color <> '' then TableB.Color
ELSE 'n/a'
end as Color
FROM TableA
LEFT JOIN TableB ON (TableA.ContractNo = TableB.ContractNo)
ORDER BY TableA.ContractNo
Can anyone help out with this?

When make concatenation sql string query , error has occurred because single quote

SET #InventoryQuery = N'SELECT * FROM
(
SELECT Inven.Inventory_ID As ID,Inven.Inventory_ID As Number, Inventory_Date As ActionDate, ''Inventory'' AS [ActionType], IsNull(Sum(Product_Qty),0) Product_Qty, P.Product_Desc_ENG + '' ('' + P.Product_Weight + '')'' Product_Desc_ENG
FROM CRM.Product P
INNER JOIN [crm].[InventoryDetail] InvenDet ON P.Product_ID = InvenDet.Product_ID
INNER JOIN [crm].[Inventory] Inven ON Inven.Inventory_ID = InvenDet.Inventory_ID
WHERE Inven.Customer_Id = ' + CAST(#CustomerID AS VARCHAR(10)) +
' AND ( Inven.Inventory_Date BETWEEN ' + CONVERT(VARCHAR(20), #StartDate, 121) + '
AND ' + CONVERT(VARCHAR(20), #EndDate, 121) + ' ) GROUP BY Inven.Inventory_ID, Inventory_Date,P.Product_Desc_ENG,P.Product_Weight
) y
pivot
(
sum(Product_Qty)
for Product_Desc_ENG in (' + #cols + N')
) p2 '

SQL multiple where clauses

I have a procedure that has the options to take in Ids from three different columns I am concatenating all the where clauses together and then I EXEC the command.
Just wanted to see if there is a better way to do this?
IF ((ISNULL(#GuidelineIds, '')) <> '')
BEGIN
SET #whereClause = #whereClause + ' AND glinks.GuidelineId IN (SELECT val AS linkType FROM dbo.Split(''' + #GuidelineIds + ''','',''))'
END
IF ((ISNULL(#SubCategories, '')) <> '')
BEGIN
SET #whereClause = #whereClause + ' AND lt.LinkTypeID IN (SELECT val As subCategories FROM dbo.Split(''' + #SubCategories + ''', '',''))'
END
IF ((ISNULL(#LanguageIds, '')) <> '')
BEGIN
SET #whereClause = #whereClause + ' AND glinks.LanguageId IN (SELECT val As languages FROM dbo.Split(''' + #LanguageIds + ''', '',''))'
END
You can achieve it by this way
Select *
From ...
WHERE 1 = 1
AND ((ISNULL(#GuidelineIds, '')) = '' OR glinks.GuidelineId IN (SELECT val AS linkType FROM dbo.Split(''' + #GuidelineIds + ''','','')))
AND ((ISNULL(#SubCategories, '')) = '' OR lt.LinkTypeID IN (SELECT val As subCategories FROM dbo.Split(''' + #SubCategories + ''', '','')))
AND ((ISNULL(#LanguageIds, '')) = '' OR glinks.LanguageId IN (SELECT val As languages FROM dbo.Split(''' + #LanguageIds + ''', '','')))

SQL results to Outlook VCard?

I need to export SQL records to outlook vcards, so 1 vcard per result row returned. Does anyone know how to do this?
Maybe something like this:
DECLARE #crlf char(2)
SET #crlf = CHAR(13) + CHAR(10)
SELECT
'BEGIN:VCARD' + #crlf
+ COALESCE ('N:' + COALESCE (Last, '') + ';'
+ COALESCE (First, '') + ';'
+ COALESCE (Mi, '') + #crlf, '')
+ COALESCE ('FN:' + FullName + #crlf, '')
+ COALESCE ('TITLE:' + Title + #crlf, '')
+ COALESCE ('ORG:' + Company + #crlf, '')
+ COALESCE ('TEL;WORK;VOICE:' + PhoneWork + #crlf, '')
+ COALESCE ('TEL;WORK;FAX:' + FaxWork + #crlf, '')
+ COALESCE ('TEL;HOME;VOICE:' + [PhoneHome] + #crlf, '')
+ COALESCE ('TEL;HOME;FAX:' + [FaxHome] + #crlf, '')
+ COALESCE ('TEL;CELL;VOICE:' + [PhoneMobile] + #crlf, '')
+ COALESCE ('TEL;PAGER;VOICE:' + [Pager] + #crlf, '')
+ 'ADR;WORK:;;' + COALESCE ([Address], '') + ';'
+ COALESCE ([City], '') + ';' + COALESCE ([State], '') + ';'
+ COALESCE ([Zip], '') + #crlf
+ COALESCE ('EMAIL;PREF;INTERNET:' + [email] + #crlf, '')
+ 'REV:' + { fn REPLACE({ fn REPLACE(
{ fn REPLACE(CONVERT(varchar, GETDATE(), 120), '-', '')
}, ':', '') }, ' ', 'T') } + 'Z'+ #crlf
+ 'END:VCARD' + #crlf AS vcard
FROM
yourTable

How to concatenate strings and commas in SQL Server?

I'm relatively new to MSSQL, so sorry if the question might sounds trivial. I want to concatenate multiple fields with a delimiter ,. However, when the field is empty, the extra , will be included in the result string as well. So is there an easy way to solve this problem? For example,
SELECT VRI.Street_Number_and_Modifier + ',' +
VRI.Street_Direction + ',' +
VRI.Street_Name + ',' +
VRI.Street_Direction + ',' +
VRI.Street_Suffix + ',' +
VRI.Street_Post_Direction + ',' +
VRI.Unit
FROM View_Report_Information_Tables VRI
This modified version of Lamak's handles NULL or strings containing only space/empty:
SELECT COALESCE(NULLIF(VRI.Street_Number_and_Modifier, '') + ',', '') +
COALESCE(NULLIF(VRI.Street_Direction, '') + ',', '') +
COALESCE(NULLIF(VRI.Street_Name, '') + ',', '') +
COALESCE(NULLIF(VRI.Street_Direction, '') + ',', '') +
COALESCE(NULLIF(VRI.Street_Suffix, '') + ',', '') +
COALESCE(NULLIF(VRI.Street_Post_Direction, '') + ',', '') +
COALESCE(NULLIF(VRI.Unit, ''), '')
FROM View_Report_Information_Tables VRI
I was able to get it to work with a slightly different approach. Putting the commas at the beginning of each field and then removing the first one with the STUFF function worked for me:
SELECT
STUFF((COALESCE(', ' + NULLIF(VRI.Street_Number_and_Modifier, ''), '') +
COALESCE(', ' + NULLIF(VRI.Street_Direction, ''), '') +
COALESCE(', ' + NULLIF(VRI.Street_Name, ''), '')) +
COALESCE(', ' + NULLIF(VRI.Street_Direction, ''), '')) +
COALESCE(', ' + NULLIF(VRI.Street_Suffix, ''), '')) +
COALESCE(', ' + NULLIF(VRI.Street_Post_Direction, ''), '')) +
COALESCE(', ' + NULLIF(VRI.Unit, ''), ''))
, 1, 2, '')
FROM View_Report_Information_Tables AS VRI
If the columns are empty instead of null, you can try this:
SELECT VRI.Street_Number_and_Modifier
+ CASE WHEN VRI.Street_Number_and_Modifier <> '' THEN ', ' ELSE '' END
+ VRI.Street_Direction
+ CASE WHEN VRI.Street_Direction <> '' THEN ', ' ELSE '' END
+ VRI.Street_Name
+ CASE WHEN VRI.Street_Name <> '' THEN ', ' ELSE '' END
+ VRI.Street_Direction
+ CASE WHEN VRI.Street_Direction <> '' THEN ', ' ELSE '' END
+ VRI.Street_Suffix
+ CASE WHEN VRI.Street_Suffix <> '' THEN ', ' ELSE '' END
+ VRI.Street_Post_Direction
+ CASE WHEN VRI.Street_Post_Direction <> '' THEN ', ' ELSE '' END
+ VRI.Unit
+ CASE WHEN VRI.Unit<> '' THEN ', ' ELSE '' END
FROM View_Report_Information_Tables VRI
For SQL 2008+
Using
ISNULL(Colmn1 + ', ', '')
Will always result with a leading comma in the end, so you'll have to handle it.
Example:
DECLARE #Column1 NVARCHAR(10) = 'Column1'
, #Column2 NVARCHAR(10) = 'Column2'
SELECT SUBSTRING( ISNULL(#Column1 + ', ', '') + ISNULL(#Column2 + ', ', '')
, 0 --Starting from 0 not 1 to remove leading comma
, LEN(ISNULL(#Column1 + ', ', '') + ISNULL(#Column2 + ', ', '')))
Or we could approach this the other way around and use the STUFF function to remove our beginning comma which looks cleaner, example:
SELECT STUFF (ISNULL(( ', ' + #Column1), '') + ISNULL(( ', ' + #Column2), ''), 1, 2, N'')
For SQL 2012+ we could use the CONCAT function and remove beginning comma using STUFF similar to our previous example but avoiding ISNULL:
SELECT STUFF(CONCAT( ', ' + #Column1, ', ' + #Column2), 1, 2, N'')
For SQL 2017+ CONCAT_WS was introduced where you can concatinate/join multiple string columns with a delimiter specified in the first argument of the function:
MS Documents CONCAT_WS
MS Doc Example:
SELECT CONCAT_WS(',' --delimiter
,'1 Microsoft Way', NULL, NULL, 'Redmond', 'WA', 98052) AS Address;
Try this:
SELECT COALESCE(VRI.Street_Number_and_Modifier + ',','') +
COALESCE(VRI.Street_Direction + ',','') +
COALESCE(VRI.Street_Name + ',','') +
COALESCE(VRI.Street_Direction + ',','') +
COALESCE(VRI.Street_Suffix + ',','') +
COALESCE(VRI.Street_Post_Direction + ',','') +
COALESCE(VRI.Unit,'')
FROM View_Report_Information_Tables VRI
Short or long answer?
Short answer - dont. This is a formatting issue, not a database issue.
Long answer - When you concatenate a string and a null in sql server, the result is null. So you can use combinations of ISNULL
SELECT ISNULL(afield + ',','') + ISNULL(bfield + ',','')
You have to use select case when IsNull(fieldname, '')= '' or ltrim(rtrim(fieldname))='') Then ... Else... end +...
Edit:
Was written from Android mobile.
Below your example.
The following translations (from German) apply, FYI:
Vorname: given name
Name: surname
Benutzer: User
And here's the example code:
CREATE VIEW [dbo].[V_RPT_SEL_Benutzer]
AS
SELECT
BE_ID AS RPT_UID,
CASE
WHEN (ISNULL(BE_Name, '0') = '0' OR LTRIM(RTRIM(BE_Name)) = '') AND (ISNULL(BE_Vorname, '0') = '0' OR LTRIM(RTRIM(BE_Vorname)) = '')
THEN ''
WHEN (ISNULL(BE_Name, '0') = '0' OR LTRIM(RTRIM(BE_Name)) = '')
THEN ISNULL(BE_Vorname, '')
WHEN (ISNULL(BE_Vorname, '0') = '0' OR LTRIM(RTRIM(BE_Vorname)) = '')
THEN ISNULL(BE_Name, '')
ELSE
ISNULL(BE_Name, '') + ', ' + ISNULL(BE_Vorname, '')
END AS RPT_Name,
ROW_NUMBER() OVER (ORDER BY BE_Name, BE_Vorname ASC) AS RPT_Sort
FROM T_Benutzer
You could use the ISNULL(field + ',', '')
SELECT isnull(VRI.Street_Number_and_Modifier + ',','')+
isnull(VRI.Street_Direction + ',','')+
isnull(VRI.Street_Name + ',','')+
isnull(VRI.Street_Direction + ',','')+
isnull(VRI.Street_Suffix + ',','')+
isnull(VRI.Street_Post_Direction + ',','')+
isnull(VRI.Unit,'')
FROM View_Report_Information_Tables VRI
I would agree completely with Jamiec's short answer.
Otherwise, I would look at a nasty solution of using a REPLACE([concat], ',,', ',') everywhere you concatenate two columns, and then figure out how to trim commas from the beginning and end of the string where the first and last columns might be empty. Very very messy.
Wanted to see if I can get it without using CASE but could not. A long-winded way of mine:
SELECT case when isnull(nullif(VRI.Street_Number_and_Modifier, ''),'')='' then '' else VRI.Street_Number_and_Modifier end
+ case when isnull(nullif(VRI.Street_Direction, ''),'')='' then '' else ',' + VRI.Street_Direction end
+ case when isnull(nullif(VRI.Street_Name, ''),'')='' then '' else ',' + VRI.Street_Name end
+ case when isnull(nullif(VRI.Street_Suffix, ''),'')='' then '' else ',' + VRI.Street_Suffix end
+ case when isnull(nullif(VRI.Street_Post_Direction, ''),'')='' then '' else ',' + VRI.Street_Post_Direction end
+ case when isnull(nullif(VRI.Street_Post_Direction, ''),'')='' then '' else ',' + VRI.Street_Post_Direction end
FROM View_Report_Information_Tables VRI
SELECT COALESCE(NULLIF(ad.UDEFPROPERTYADDRESS_ADDRSS_LN_1_TXT, ''), ',')+
COALESCE(NULLIF(ad.UDEFPROPERTYADDRESS_ADDRSS_LN_2_TXT, '') , ',')+
COALESCE(NULLIF(ad.UDEFPROPERTYADDRESS_ADDRSS_LN_3_TXT, '') , ',')+
COALESCE(NULLIF(ad.UDEFPROPERTYADDRESS_CITY_TXT, '') , ',')+
COALESCE(NULLIF(ad.UDEFPROPERTYADDRESS_ST_TXT, '') , ',')+
COALESCE(NULLIF(ad.UDEFPROPERTYADDRESS_CNTRY_TXT, '') , ',')+
COALESCE(NULLIF(ad.UDEFPROPERTYADDRESS_PSTL_CD, '') , '')
FROM ACCOUNT_DETAILS ad
This will not add any commas if null-strings
SELECT CONCAT_WS(', ', IFNULL(column1, NULL),
IFNULL(column2, NULL), IFNULL(column3, NULL),
IFNULL(column4, NULL), IFNULL(column5, NULL))
FROM yourtable