XML for path query to T-SQL query - sql

I have a pretty complex query that uses the 'XML for path' to return an XML. Now I need this query as a regular T-SQL query, but I have great difficulty converting this. I have searched for a tool or another topic that can convert this or give more information how to easily transform this query to a regular t-sql query. Any help would be greatly appreciated!
SELECT
UPPER([dataareaid]) AS Company,
accountnum AS Code,
name + ' [' +
CASE ENTERPRISENUMBER
WHEN 'BTW BE 0000.000.097'
THEN TMMONATIONALREGISTRATIONNUMBER
ELSE
CASE countryregionid
WHEN 'BE'
THEN ENTERPRISENUMBER
ELSE countryregionid + VATNUM
END
END + ']' AS Name,
'false' AS PaymentDenied,
PAYMTERMID AS PaymentTermCode,
currency AS Currency,
AX_TMM.dbo.IS_ACCOUNT_ACTIVE(dataareaid,accountnum) AS Active,
--recid AS Id,
'email' as OrderFormat,
'efinance#test.be' as OrderEmail,
'nl-NL' as [Language],
CASE ENTERPRISENUMBER
WHEN 'BTW BE 0000.000.097'
THEN REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(TMMONATIONALREGISTRATIONNUMBER, '.', ''), ',', ''),'-',''),' ', ''),'BTW', '')
ELSE
CASE countryregionid
WHEN 'BE'
THEN REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(ENTERPRISENUMBER, '.', ''), ',', ''),'-',''),' ', ''),'BTW', '')
ELSE REPLACE(REPLACE(REPLACE(REPLACE(REPLACE((countryregionid + VATNUM), '.', ''), ',', ''),'-',''),' ', ''),'BTW', '')
END
END AS [SupplierIdentifiers/SupplierIdentifier/value],
'PartyId' AS [SupplierIdentifiers/SupplierIdentifier/key],
CASE ENTERPRISENUMBER
WHEN 'BTW BE 0000.000.097'
THEN REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(TMMONATIONALREGISTRATIONNUMBER, '.', ''), ',', ''),'-',''),' ', ''),'BTW', '')
ELSE
CASE countryregionid
WHEN 'BE'
THEN REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(ENTERPRISENUMBER, '.', ''), ',', ''),'-',''),' ', ''),'BTW', '')
ELSE REPLACE(REPLACE(REPLACE(REPLACE(REPLACE((countryregionid + VATNUM), '.', ''), ',', ''),'-',''),' ', ''),'BTW', '')
END
END AS [AdditionalDatas/AdditionalData/value],
'PartyId' AS [AdditionalDatas/AdditionalData/name],
(SELECT
accountnum AS [Bban],
ACCOUNTID AS [Name],
name AS [AdditionalData1],
ENTERPRISENUMBER AS [AdditionalData2],
bankiban AS [Iban],
swiftno AS [Swift],
AX_TMM.dbo.IS_BANKACCOUNT_DEFAULT(dataareaid,vendaccount,accountid) AS IsDefault
--vendtable.recid AS Supplierid
FROM
vendbankaccount
WHERE
vendaccount = vendtable.accountnum
and DATAAREAID = vendtable.DATAAREAID
and (expirydate = '1900-01-01 00:00:00.000' or expirydate > getdate())
FOR xml path('SupplierBankAccount'), TYPE) AS [BankAccounts],
(SELECT (SELECT
'' AS [ExternalCode],
'PostalAddress' AS [Type],
'Maatschappelijke zetel ' + SMARTMDCMASTERACCOUNTTABLE.NAME AS [Name],
'true' AS [IsDefault],
maaccount + vendtable.DATAAREAID AS [ExternalIdentifier],
(SELECT (SELECT
'STREET_NAME' AS [AddressPartKey],
street AS [AddressPartText]
FROM
SMARTMDCMASTERACCOUNTTABLE
LEFT OUTER JOIN ADDRESSCOUNTRYREGION
ON ADDRESSCOUNTRYREGION.ISOCODE = SMARTMDCMASTERACCOUNTTABLE.country
AND ADDRESSCOUNTRYREGION.DATAAREAID = SMARTMDCMASTERACCOUNTTABLE.DATAAREAID
WHERE
maaccount = vendtable.accountnum
FOR xml path('SupplierAddressPart'), TYPE),
(SELECT
'POSTAL_ZONE' AS [AddressPartKey],
zipcode AS [AddressPartText]
FROM
SMARTMDCMASTERACCOUNTTABLE
WHERE
maaccount = vendtable.accountnum
FOR xml path('SupplierAddressPart'), TYPE
),
(SELECT
'CITY_NAME' AS [AddressPartKey],
city AS [AddressPartText]
FROM
SMARTMDCMASTERACCOUNTTABLE
WHERE
maaccount = vendtable.accountnum
FOR xml path('SupplierAddressPart'), TYPE
),
(SELECT
'COUNTRY' AS [AddressPartKey],
ADDRESSCOUNTRYREGION.NAME AS [AddressPartText]
FROM
SMARTMDCMASTERACCOUNTTABLE
LEFT OUTER JOIN ADDRESSCOUNTRYREGION
ON ADDRESSCOUNTRYREGION.ISOCODE = SMARTMDCMASTERACCOUNTTABLE.country
AND ADDRESSCOUNTRYREGION.DATAAREAID = SMARTMDCMASTERACCOUNTTABLE.DATAAREAID
WHERE
maaccount = vendtable.accountnum
FOR xml path('SupplierAddressPart'), TYPE
)
FOR xml path('AddressParts'), TYPE)
FROM
SMARTMDCMASTERACCOUNTTABLE
LEFT OUTER JOIN ADDRESSCOUNTRYREGION
ON ADDRESSCOUNTRYREGION.ISOCODE = SMARTMDCMASTERACCOUNTTABLE.country
AND ADDRESSCOUNTRYREGION.DATAAREAID = SMARTMDCMASTERACCOUNTTABLE.DATAAREAID
WHERE
maaccount = vendtable.accountnum
FOR xml path('SupplierAddress'), TYPE) FOR xml path('SupplierAddresses'), TYPE)
FROM vendtable
WHERE DATAAREAID = 'TMM'
FOR xml path('Supplier'), ROOT ('DocumentElement')

Related

Show unique values only when using CTE - SQL Server

I have the following query:
with GTS_cte AS
(SELECT distinct [BusinessTermID], GTS_T =
STUFF ((SELECT ', ' + dbo.TblField.GTS_table
FROM dbo.TblField
WHERE [BusinessTermID] = Y.[BusinessTermID] AND dbo.TblField.GTS_table <> '' FOR XML PATH('')), 1, 2, '')
FROM dbo.Tblfield AS Y
GROUP BY [BusinessTermID])
,
syn_cte as (
SELECT [BusinessTermID], syns = STUFF
((SELECT ', ' + dbo.TblBusinessSynonym.Synonym
FROM dbo.TblBusinessSynonym
WHERE [BusinessTermID] = x.[BusinessTermID] AND dbo.TblBusinessSynonym.Synonym <> '' FOR XML PATH('')), 1, 2, '')
FROM dbo.TblBusinessSynonym AS x
GROUP BY [BusinessTermID])
select syn_cte.BusinessTermID, syn_cte.syns, GTS_cte.GTS_T
from syn_cte join
GTS_cte on GTS_cte.BusinessTermID = syn_cte.BusinessTermID
It is concatenating the fields correctly and linking them but it is now creating duplicates. My result set looks like this:
Is there a way to show only Unique values in GTS_T?
Thank you
Use DISTINCT inside your Sub-Query.
Try this:
;with GTS_cte AS
(SELECT [BusinessTermID], GTS_T =
STUFF ((SELECT DISTINCT ', ' + dbo.TblField.GTS_table
FROM dbo.TblField
WHERE [BusinessTermID] = Y.[BusinessTermID] AND dbo.TblField.GTS_table <> '' FOR XML PATH('')), 1, 2, '')
FROM dbo.Tblfield AS Y
GROUP BY [BusinessTermID])
,
syn_cte as (
SELECT [BusinessTermID], syns = STUFF
((SELECT DISTINCT ', ' + dbo.TblBusinessSynonym.Synonym
FROM dbo.TblBusinessSynonym
WHERE [BusinessTermID] = x.[BusinessTermID] AND dbo.TblBusinessSynonym.Synonym <> '' FOR XML PATH('')), 1, 2, '')
FROM dbo.TblBusinessSynonym AS x
GROUP BY [BusinessTermID])
select syn_cte.BusinessTermID, syn_cte.syns, GTS_cte.GTS_T
from syn_cte join
GTS_cte on GTS_cte.BusinessTermID = syn_cte.BusinessTermID

Column Name or number of supplied values does not match table definition (table definition is identical with what has been supplied)

I have taken into account all your suggestions and amended the code however I am still getting the same error even though I have checked the query and the table definition all morning long. What are your views on this?
CREATE TABLE #tempNonInvoicedExportResults
(
DateCreated DATE ,
DestinationCountry CHAR(2) ,
DestinationDepot CHAR(3) ,
MovementRef CHAR(12) ,
TotalCons INT ,
SailingDate DATETIME ,
TrailerNumber VARCHAR(50) ,
TotalEstimatedChargeableWeight DECIMAL NULL ,
PayableInUK BIT NULL ,
HasLongLengthConsignments BIT ,
CountOfConsOnMovement VARCHAR (100)
)
INSERT INTO #tempNonInvoicedExportResults
SELECT
CAST(CON.[Date Loaded] AS DATE) as DateCreated,
ISNULL(STUFF(( SELECT DISTINCT '/' + COALESCE(cr2.DestinationCountry, 'NA')
FROM movMovement mov2
INNER JOIN movConLink mcl2 ON mcl2.MovementID = mov2.MovementID
INNER JOIN cgtRoute cr2 ON cr2.RouteID = mcl2.CMRRouteID
WHERE cr2.DestinationCountry <> 'GB'
AND cr2.RouteID = mcl2.CMRRouteID
AND mov2.MovementID = MM.MovementID
FOR XML PATH('')), 1, 1, ''), '') AS DestinationCountry,
ISNULL(STUFF(( SELECT DISTINCT '/' + COALESCE(cr2.DestinationDepot, 'NA')
FROM movMovement mov2
INNER JOIN movConLink mcl2 ON mcl2.MovementID = mov2.MovementID
INNER JOIN cgtRoute cr2 ON cr2.RouteID = mcl2.CMRRouteID
WHERE cr2.DestinationCountry <> 'GB'
AND cr2.RouteID = mcl2.CMRRouteID
AND mov2.MovementID = MM.MovementID
FOR XML PATH('')), 1, 1, ''), '') AS DestinationDepot,
CASE WHEN PATINDEX('%[A-Z][A-Z][A-Z][A-Z][0-9][0-9][0-9][0-9][0-9]%',
REPLACE(MU.Number, '-', '')) > 0
THEN STUFF(STUFF(SUBSTRING(REPLACE(MU.Number, '-', ''),
PATINDEX('%[A-Z][A-Z][A-Z][A-Z][0-9][0-9][0-9][0-9][0-9]%',
REPLACE(MU.Number, '-', '')), 10), 3, 0, '-'), 6, 0, '-') ELSE MM.MovementRef END AS MovementRef,
COUNT(MCL.ConsignmentReference) AS TotalCons,
MM.SailingDateTime as SailingDate,
MU.Number as TrailerNumber,
SUM(EstimatedChargeableWeight) as TotalEstimatedChargeableWeight,
UKPayable as PayableInUK,
tl.HasLongLengthConsignments as HasLongLengthConsignments,
CASE WHEN COUNT(MCL.ConsignmentReference) < 3 THEN 'Movement has 3 or less cons' ELSE 'Movement has 3 or more cons' END AS CountOfConsOnMovement
First do SELECT INTO a permanent table dbo.tmp like this (add your from clause):
SELECT
CAST(CON.[Date Loaded] AS DATE) as DateCreated, /*1*/
ISNULL(STUFF(( SELECT DISTINCT '/' + COALESCE(cr2.DestinationCountry, 'NA')
FROM movMovement mov2
INNER JOIN movConLink mcl2 ON mcl2.MovementID = mov2.MovementID
INNER JOIN cgtRoute cr2 ON cr2.RouteID = mcl2.CMRRouteID
WHERE cr2.DestinationCountry <> 'GB'
AND cr2.RouteID = mcl2.CMRRouteID
AND mov2.MovementID = MM.MovementID
FOR XML PATH('')), 1, 1, ''), '') AS DestinationCountry, /*2*/
ISNULL(STUFF(( SELECT DISTINCT '/' + COALESCE(cr2.DestinationDepot, 'NA')
FROM movMovement mov2
INNER JOIN movConLink mcl2 ON mcl2.MovementID = mov2.MovementID
INNER JOIN cgtRoute cr2 ON cr2.RouteID = mcl2.CMRRouteID
WHERE cr2.DestinationCountry <> 'GB'
AND cr2.RouteID = mcl2.CMRRouteID
AND mov2.MovementID = MM.MovementID
FOR XML PATH('')), 1, 1, ''), '') AS DestinationDepot, /*3*/
CASE WHEN PATINDEX('%[A-Z][A-Z][A-Z][A-Z][0-9][0-9][0-9][0-9][0-9]%',
REPLACE(MU.Number, '-', '')) > 0
THEN STUFF(STUFF(SUBSTRING(REPLACE(MU.Number, '-', ''),
PATINDEX('%[A-Z][A-Z][A-Z][A-Z][0-9][0-9][0-9][0-9][0-9]%',
REPLACE(MU.Number, '-', '')), 10), 3, 0, '-'), 6, 0, '-') ELSE MM.MovementRef END AS MovementRef, /*4*/
COUNT(MCL.ConsignmentReference) AS TotalCons, /*5*/
MM.SailingDateTime as SailingDate, /*6*/
MU.Number as TrailerNumber, /*7*/
SUM(EstimatedChargeableWeight) as TotalEstimatedChargeableWeight, /*8*/
UKPayable as PayableInUK, /*9*/
tl.HasLongLengthConsignments as HasLongLengthConsignments, /*10*/
CASE WHEN COUNT(MCL.ConsignmentReference) < 3 THEN 'Movement has 3 or less cons' ELSE 'Movement has 3 or more cons' END AS CountOfConsOnMovement /*11*/
into dbo.tmp
from ...
Once you have created dbo.tmp, find it in Management Studio and Script it as CREATE
In the generated script change dbo.tmp to #tempNonInvoicedExportResults

Execute the SQL query with if statement in Where clause

Need to execute the SQL query with IF statement in Where clause.
SELECT
CASE
WHEN Isnull(CustGuarFlag ,'') = '' THEN DocName
ELSE DocName + ' - '+
CASE
WHEN CustGuarFlag= 'C' THEN 'Customer'
ELSE 'Guarantor'
END
END DocName,
ISNULL(A.DOCSTAGE, '') DOCSTAGE,
ISNULL(A.DOCREFNO,'') DOCREFNO,
ISNULL(CONVERT(VARCHAR, A.DOCREFDT, 103), '') DOCREFDT,
ISNULL(CONVERT(VARCHAR, A.RECDDT, 103), '') RECDDT ,
ISNULL(A.DOCVALUE, 0) DOCVALUE ,
ISNULL(CONVERT(VARCHAR, A.DOCVLDUPTO, 103), '') DOCVLDUPTO,
a.pk_id AS AppDocpk,
b.pk_id AS Docpk,
CASE
WHEN Isnull(a.DocVerifiedStatus, '') = 'null'
THEN ''
ELSE Isnull(a.DocVerifiedStatus,'')
END AS DocVerifiedStatus,
ISNULL(RejRemarks, '') AS RejRemarks,
ISNULL(KYCDocHdr_Fk, 0) AS KYCPk,
ISNULL(DocShrtDescr, '') AS DocShrtDescr
FROM
loln_apprvldoc A WITH(NOLOCK)
JOIN
LGEN_DOCUMENTS B WITH(NOLOCK) ON A.Doc_FK = B.PK_ID
LEFT OUTER JOIN
Lgen_KYCApprvlDoc c ON a.KYCDocHdr_Fk = c.PK_Id
WHERE
A.PRPSLNO = 'KATHU1602080002'
AND ISNULL(A.DocStat, '') = 'R'
AND ISNULL(A.DocVerifiedStatus, '') IN ('Rejection', '', 'null')
AND CASE
WHEN Isnull(c.DocVerifiedStatus, '') = 'A'
THEN c.Pk_id IS NOT NULL
ELSE c.Pk_id IS NULL
END
CASE doesn't belong in a WHERE clause. Replace that CASE clause with
(
(Isnull(c.DocVerifiedStatus,'')='A' AND c.Pk_id IS NOT NULL)
OR
(Isnull(c.DocVerifiedStatus,'')<>'A' AND c.Pk_id IS NULL)
)

Showing a row that doesn't exist

I have a select that fetches some data for me.
I'm trying to make a query that shows me that data but if it doesn't exist it will show me the first 5 columns with data that I provided. Here is the query
DECLARE #miesiac INT = 1
DECLARE #opis VARCHAR(30) = '';
WITH cte
AS ( SELECT DISTINCT
ROW_NUMBER() OVER ( PARTITION BY emp_name,
doc_documentdate ORDER BY doc_documentdate ) s
,emp_name Kod
,emp_id id
,Emp_Surname Nazwisko
,Emp_FirstName Imie
,ISNULL(CONVERT(VARCHAR(10), Doc_DocumentDate, 120), '') Data
,CASE WHEN doc_documentdate = ttc_date
AND ttc_isholiday = 0 THEN 'S'
WHEN doc_documentdate = ttc_date
AND ttc_isholiday = 6
OR ttc_isholiday = 7
OR ELM_DecimalColumn1 = 0 THEN 'W'
WHEN ELM_DecimalColumn1 IS NULL THEN 'w'
ELSE 'P'
END Typdnia
,ISNULL(CONVERT(VARCHAR(8), elm_datecolumn1, 108),
'00:00:00') GodzOd
,ISNULL(CONVERT(VARCHAR(8), elm_datecolumn2, 108),
'00:00:00') GodzDo
,CASE WHEN ELM_decimalcolumn1 > 0
THEN 'praca podstawowa'
ELSE 'brak'
END Strefa
,#opis Opis
,ISNULL(emp_shortstringcolumn2, 'brak') Wydzial
,ISNULL(ELM_ShortStringColumn5, '0') Wydzial_adres_wezla
,ISNULL(a.dic_svalue, ' brak') Projekt
,ISNULL(b.DIC_ShortStringColumn1, '1') Projekt_adres_wezla
FROM Employees
LEFT JOIN elements ON emp_id = ELM_EmpID
AND ELM_FflID = 200
LEFT JOIN documents ON elm_objectid = doc_id
AND Doc_DdfID = 2
LEFT JOIN dictionaries a ON ELM_IntColumn2 = a.DIC_ID
LEFT JOIN Dictionaries b ON elm_intcolumn2 = b.DIC_ID
LEFT JOIN ttscalendar ON ttc_date = Doc_DocumentDate
RIGHT JOIN dim_timeday ON doc_documentdate = tmd_fulldatekey
)
SELECT ISNULL(cte1.kod, '') Kod
,ISNULL(cte1.nazwisko, '') Nazwisko
,ISNULL(cte1.imie, '') Imie
,ISNULL(cte1.data, '') Data
,ISNULL(cte1.TypDnia, '') Typdnia
,ISNULL(cte1.GodzOd, '00:00') W1_GodzOd
,ISNULL(cte1.godzdo, '00:00') W1_GodzDo
,ISNULL(cte1.strefa, 'brak') W1_Strefa
,ISNULL(cte1.opis, '') W1_Opis
,ISNULL(cte1.wydzial, 'brak') W1_Wydzial
,ISNULL(cte1.wydzial_adres_wezla, '0') W1_Wydzial_adres_wezla
,ISNULL(cte1.Projekt, 'brak') W1_Projekt
,ISNULL(cte1.Projekt_adres_wezla, '1') W1_Projekt_adres_wezla
,ISNULL(cte2.GodzOd, '') W2_GodzOd
,ISNULL(cte2.godzdo, '') W2_GodzDo
,ISNULL(cte2.strefa, '') W2_Strefa
,ISNULL(cte2.opis, '') W2_Opis
,ISNULL(cte2.wydzial, '') W2_Wydzial
,ISNULL(cte2.wydzial_adres_wezla, '') W2_Wydzial_adres_wezla
,ISNULL(cte2.Projekt, '') W2_Projekt
,ISNULL(cte2.Projekt_adres_wezla, '') W2_Projekt_adres_wezla
,ISNULL(cte3.GodzOd, '') W3_GodzOd
,ISNULL(cte3.godzdo, '') W3_GodzDo
,ISNULL(cte3.strefa, '') W3_Strefa
,ISNULL(cte3.opis, '') W3_Opis
,ISNULL(cte3.wydzial, '') W3_Wydzial
,ISNULL(cte3.wydzial_adres_wezla, '') W3_Wydzial_adres_wezla
,ISNULL(cte3.Projekt, '') W3_Projekt
,ISNULL(cte3.Projekt_adres_wezla, '') W3_Projekt_adres_wezla
,ISNULL(cte4.GodzOd, '') W4_GodzOd
,ISNULL(cte4.godzdo, '') W4_GodzDo
,ISNULL(cte4.strefa, '') W4_Strefa
,ISNULL(cte4.opis, '') W4_Opis
,ISNULL(cte4.wydzial, '') W4_Wydzial
,ISNULL(cte4.wydzial_adres_wezla, '') W4_Wydzial_adres_wezla
,ISNULL(cte4.Projekt, '') W4_Projekt
,ISNULL(cte4.Projekt_adres_wezla, '') W4_Projekt_adres_wezla
,ISNULL(cte5.GodzOd, '') W5_GodzOd
,ISNULL(cte5.godzdo, '') W5_GodzDo
,ISNULL(cte5.strefa, '') W5_Strefa
,ISNULL(cte5.opis, '') W5_Opis
,ISNULL(cte5.wydzial, '') W5_Wydzial
,ISNULL(cte5.wydzial_adres_wezla, '') W5_Wydzial_adres_wezla
,ISNULL(cte5.Projekt, '') W5_Projekt
,ISNULL(cte5.Projekt_adres_wezla, '') W5_Projekt_adres_wezla
,ISNULL(cte6.GodzOd, '') W6_GodzOd
,ISNULL(cte6.godzdo, '') W6_GodzDo
,ISNULL(cte6.strefa, '') W6_Strefa
,ISNULL(cte6.opis, '') W6_Opis
,ISNULL(cte6.wydzial, '') W6_Wydzial
,ISNULL(cte6.wydzial_adres_wezla, '') W6_Wydzial_adres_wezla
,ISNULL(cte6.Projekt, '') W6_Projekt
,ISNULL(cte6.Projekt_adres_wezla, '') W6_Projekt_adres_wezla
FROM cte cte1
LEFT JOIN cte cte2 ON cte1.Kod = cte2.kod
AND cte1.data = cte2.data
AND cte2.s = 2
LEFT JOIN cte cte3 ON cte2.Kod = cte3.kod
AND cte2.data = cte3.data
AND cte3.s = 3
LEFT JOIN cte cte4 ON cte3.Kod = cte4.kod
AND cte3.data = cte4.data
AND cte4.s = 4
LEFT JOIN cte cte5 ON cte4.Kod = cte5.kod
AND cte4.data = cte5.data
AND cte5.s = 5
LEFT JOIN cte cte6 ON cte5.Kod = cte6.kod
AND cte5.data = cte6.data
AND cte6.s = 6
WHERE cte1.s = 1
AND MONTH(cte1.data) = #Miesiac
AND cte1.id = 7
ORDER BY cte1.data
,cte1.kod
Here is the data
ANJO_141 ANTONKIEWICZ JOLANTA 2016-01-22 S 00:00:00 00:00:00 brak NF 1.8 brak 1
ANJO_141 ANTONKIEWICZ JOLANTA 2016-01-23 W 07:00:00 12:00:00 praca podstawowa NF 1.8 brak 1
ANJO_141 ANTONKIEWICZ JOLANTA 2016-01-27 P 07:00:00 15:00:00 praca podstawowa NF 1.8 brak 1
ANJO_141 ANTONKIEWICZ JOLANTA 2016-01-28 W 00:00:00 00:00:00 brak NF 1.8 brak 1

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