SQL results to Outlook VCard? - sql

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

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?

AS NewCompoundField - Concatenating values which may be NULL

I have the following T-SQL query;
SELECT
Site.Address1 + CHAR(13) + Site.Address2 + CHAR(13) +
Site.Address3 + CHAR(13) + Site.Town + CHAR(13) +
Site.eCounty AS SiteAddress
FROM Site
If any of the Site.AddressX fields making up SiteAddress are NULL, then SiteAddress is itself NULL. I would like a Site.AddressX field and it's following new line character to be ignored if it is NULL.
I have tried adding a CASE statement for a single field and it's new line character, but have not been able to get it to work.
SELECT
(CASE WHEN (Site.Address1 IS NULL) THEN '' ELSE Site.Address1 + CHAR(10)) +
Site.Address2 + CHAR(13) +
Site.Address3 + CHAR(13) + Site.Town + CHAR(13) +
Site.eCounty AS SiteAddress
FROM Site
How might I go about doing this?
Try this:
SELECT
COALESCE([Site].Address1 + CHAR(13), '') +
COALESCE([Site].Address2 + CHAR(13), '') +
COALESCE([Site].Address3 + CHAR(13), '') +
COALESCE([Site].Town + CHAR(13), '') +
[Site].eCounty AS SiteAddress
FROM [Site]
Try this
SELECT
CASE WHEN Site.Address1 IS NULL THEN ''
ELSE Site.Address1 + CHAR(10) +
Site.Address2 + CHAR(13) +
Site.Address3 + CHAR(13) + Site.Town + CHAR(13) +
Site.eCounty END AS SiteAddress
FROM SITE Site

SQL Server 2012 ORDER BY works differently?

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.

How to write/append text to the bottom of n SQL script?

I have the need to add/append text(SQL) to the bottom of an existing script.
I have a STORED PROCEDURE that generates INSERT statements for me. They are quit allot, so at the moment i copy and past them in the desired scripts.
This is basically what the SQL looks like:
SELECT '' + CHAR(13) + CHAR(10) + 'EXECUTE [procSystemAppEntity_InsertOrUpdate] ' + CHAR(13) + CHAR(10) + ' #SystemUID = #SystemUID' + CHAR(13) + CHAR(10)
+ ',#SystemAppCode = #SystemAppCode' + CHAR(13) + CHAR(10)
+ ',#SystemAppEntityTypeCode = N''' + saet.[SystemAppEntityTypeCode] + '''' + CHAR(13) + CHAR(10)
+ ',#SystemAppEntityUID = '''+ CAST((SELECT NEWID()) AS nvarchar(max)) + '''' + CHAR(13) + CHAR(10)
+ ',#SystemAppEntityCode = ''' + tab.name + '''' + CHAR(13) + CHAR(10)
+ ',#SystemAppEntityName = N''' + tab.name + '''' + CHAR(13) + CHAR(10)
+ ',#TableName = N''' + tab.name + '''' + CHAR(13) + CHAR(10)
+ ',#TableKeyColumnName = N''' + tab.name + 'ID''' + CHAR(13) + CHAR(10)
+ ',#TableKeyCodeColumnName = N''' + tab.name + 'Code''' + CHAR(13) + CHAR(10)
+ ',#ManagedAssemblyName = N''' + CASE WHEN #SystemAppEntityManagedAssemblyName IS NULL THEN '' ELSE #SystemAppEntityManagedAssemblyName END + '''' + CHAR(13) + CHAR(10)
+ ', #ManagedNamespace = N''' + CASE WHEN #SystemAppEntityManagedNamespace IS NULL THEN '' ELSE #SystemAppEntityManagedNamespace END + '''' + CHAR(13) + CHAR(10)
+ ', #ManagedClassName = ''' + tab.name + '''' + CHAR(13) + CHAR(10)
+ ', #IsMultiple = ' + CAST(#IsMultiple AS varchar(1)) + CHAR(13) + CHAR(10)
+ ', #IsCodeGenerated = 1' + CHAR(13) + CHAR(10)
+ ', #IsActive = 1' + CHAR(13) + CHAR(10)
+ ', #SystemAppUserID = #CreationSystemAppUserID ' + CHAR(13) + CHAR(10) + '; '
FROM sys.tables tab INNER JOIN
[SystemAppEntityType] saet ON saet.[IsMultipleEntity] = CASE WHEN RIGHT(tab.name, 1) = 's' THEN 1 ELSE 0 END AND saet.[IsNavigationEntity] = 0 AND saet.IsSystemEntity = CASE WHEN LEFT(tab.name, 3) = 'Sys' THEN 1 ELSE 0 END
WHERE (tab.name NOT IN (SELECT e.[TableName] FROM [SystemAppEntity] e))
AND (tab.name = #Code)
With an output of:
EXECUTE [procSystemAppEntity_InsertOrUpdate]
#SystemUID = #SystemUID
,#SystemAppCode = #SystemAppCode
,#SystemAppEntityTypeCode = N'App-S'
,#SystemAppEntityUID = '11E347C7-7E69-4555-A6F0-2AFE142FC25F'
,#SystemAppEntityCode = 'Revision'
,#SystemAppEntityName = N'Revision'
,#TableName = N'Revision'
,#TableKeyColumnName = N'RevisionID'
,#TableKeyCodeColumnName = N'RevisionCode'
,#ManagedAssemblyName = N'SomeManagedAssemblyName '
, #ManagedNamespace = N'SomeManagedNamespace '
, #ManagedClassName = 'Revision'
, #IsMultiple = 0
, #IsCodeGenerated = 1
, #IsIntegratedToStaging = 1
, #IsActive = 1
, #SystemAppUserID = #CreationSystemAppUserID
;
That being said, is there a way that i can maybe write/append the Output statements directly to the desired script?
I just want it to add to the bottom of the script. Is this possible and if so, how would i achive this?
SELECT '' + CHAR(13) + CHAR(10) + 'EXECUTE [procSystemAppEntity_InsertOrUpdate] ' + CHAR(13) + CHAR(10) + ' #SystemUID = #SystemUID' + CHAR(13) + CHAR(10)
+ ',#SystemAppCode = #SystemAppCode' + CHAR(13) + CHAR(10)
+ ',#SystemAppEntityTypeCode = N''' + saet.[SystemAppEntityTypeCode] + '''' + CHAR(13) + CHAR(10)
+ ',#SystemAppEntityUID = '''+ CAST((SELECT NEWID()) AS nvarchar(max)) + '''' + CHAR(13) + CHAR(10)
+ ',#SystemAppEntityCode = ''' + tab.name + '''' + CHAR(13) + CHAR(10)
+ ',#SystemAppEntityName = N''' + tab.name + '''' + CHAR(13) + CHAR(10)
+ ',#TableName = N''' + tab.name + '''' + CHAR(13) + CHAR(10)
+ ',#TableKeyColumnName = N''' + tab.name + 'ID''' + CHAR(13) + CHAR(10)
+ ',#TableKeyCodeColumnName = N''' + tab.name + 'Code''' + CHAR(13) + CHAR(10)
+ ',#ManagedAssemblyName = N''' + CASE WHEN #SystemAppEntityManagedAssemblyName IS NULL THEN '' ELSE #SystemAppEntityManagedAssemblyName END + '''' + CHAR(13) + CHAR(10)
+ ', #ManagedNamespace = N''' + CASE WHEN #SystemAppEntityManagedNamespace IS NULL THEN '' ELSE #SystemAppEntityManagedNamespace END + '''' + CHAR(13) + CHAR(10)
+ ', #ManagedClassName = ''' + tab.name + '''' + CHAR(13) + CHAR(10)
+ ', #IsMultiple = ' + CAST(#IsMultiple AS varchar(1)) + CHAR(13) + CHAR(10)
+ ', #IsCodeGenerated = 1' + CHAR(13) + CHAR(10)
+ ', #IsActive = 1' + CHAR(13) + CHAR(10)
+ ', #SystemAppUserID = #CreationSystemAppUserID ' + CHAR(13) + CHAR(10) + ';
Insert into table(...) ;'
FROM sys.tables tab INNER JOIN
[SystemAppEntityType] saet ON saet.[IsMultipleEntity] = CASE WHEN RIGHT(tab.name, 1) = 's' THEN 1 ELSE 0 END AND saet.[IsNavigationEntity] = 0 AND saet.IsSystemEntity = CASE WHEN LEFT(tab.name, 3) = 'Sys' THEN 1 ELSE 0 END
WHERE (tab.name NOT IN (SELECT e.[TableName] FROM [SystemAppEntity] e))
AND (tab.name = #Code)
What version of SQL Server are you using?
If you are using SQL Server 2008+ then you can make generate the INSERT scripts via Generate Script utility itself.
In SQL Server 2005 or before (I have tried in SQL 2K also) then there is a pretty good stroed proc which can generate the INSERT script for a given table. Check out http://vyaskn.tripod.com/code/generate_inserts.txt

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