RTRIM & LTRIM Function with Case Statement - sql

How do i use the LTRIM & RTRIM with the following SQL? I need to LTRIM and RTRIM all these fields for leading spaces
UPDATE CORE.WeccoPartyAddress
SET AddressElements = CONTROL.TrimChar(
CASE when COALESCE(Address1,'') != '' THEN Address1 + ', ' ELSE '' END +
CASE when COALESCE(Address2,'') != '' THEN Address2 + ', ' ELSE '' END +
CASE when COALESCE(Address3,'') != '' THEN Address3 + ', ' ELSE '' END +
CASE when COALESCE(Town,'') != '' THEN Town + ', ' ELSE '' END +
CASE when COALESCE(County,'') != '' THEN County + ', ' ELSE '' END +
CASE when COALESCE(Postcode,'') != '' THEN Postcode ELSE '' END, ', '
)

Use like below nested:
UPDATE CORE.WeccoPartyAddress SET AddressElements = rtrim(ltrim(CASE when COALESCE(Address1,'') != '' THEN Address1 + ', ' ELSE '' END + CASE when COALESCE(Address2,'') != '' THEN Address2 + ', ' ELSE '' END + CASE when COALESCE(Address3,'') != '' THEN Address3 + ', ' ELSE '' END + CASE when COALESCE(Town,'') != '' THEN Town + ', ' ELSE '' END + CASE when COALESCE(County,'') != '' THEN County + ', ' ELSE '' END + CASE when COALESCE(Postcode,'') != '' THEN Postcode ELSE '' END))

You don't have to use CASE in your statement
UPDATE CORE.WeccoPartyAddress
SET AddressElements = ISNULL( STUFF (
COALESCE( ', ' + LTRIM( RTRIM(Address1) ) , '') +
COALESCE( ', ' + LTRIM( RTRIM(Address1Address2) ) , '') +
COALESCE( ', ' + LTRIM( RTRIM(Address1Address3) ) , '') +
COALESCE( ', ' + LTRIM( RTRIM(Address1Town) ) , '') +
COALESCE( ', ' + LTRIM( RTRIM(Address1County) ) , '') +
COALESCE( ', ' + LTRIM( RTRIM(Address1Postcode) ) , '')
,1
,2
,''
), '')
If any of Address values is not null you will get string like this: ', Address', then using the function STUFF you replace ', ' at the beginning of the string to get 'Address' as the result.
If all values are null the STUFF function will return NULL which will be replaced with '' by ISNULL function.

Related

Syntax error in SQL , Incorrect syntax near ''

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.

Adding a '|' character to a case statement in a stored procedure

I have the following case statement in a stored procedure:
Position = case coalesce(teamMember.JobTitle, '') when '' then '' else '<b>' + coalesce(teamMember.JobTitle, '') + '</b>' end
+ isnull(teamMember.OrganizationNameLevel1, '')
+ case when isnull(teamMember.OrganizationNameLevel2, '') <> isnull(teamMember.OrganizationNameLevel1, '') THEN ' | ' + isnull(teamMember.OrganizationNameLevel2, '') ELSE '' END
+ case when isnull(teamMember.OrganizationNameLevel3, '') <> isnull(teamMember.OrganizationNameLevel2, '') THEN ' | ' + isnull(teamMember.OrganizationNameLevel3, '') ELSE '' END
+ case when isnull(teamMember.OrganizationNameLevel4, '') <> isnull(teamMember.OrganizationNameLevel3, '') THEN ' | ' + isnull(teamMember.OrganizationNameLevel4, '') ELSE '' END
+ case when isnull(teamMember.OrganizationNameLevel5, '') <> isnull(teamMember.OrganizationNameLevel4, '') THEN ' | ' + isnull(teamMember.OrganizationNameLevel5, '') ELSE '' END
+ case when isnull(teamMember.OrganizationNameLevel6, '') <> isnull(teamMember.OrganizationNameLevel5, '') THEN ' | ' + isnull(teamMember.OrganizationNameLevel6, '') ELSE '' END,
It produces the following result:
<b>APPS SYSTEMS ENGINEER</b>TECH & OPS | ENT INFO TECH | DEP & OPS TECH | HR SYS & ITECH | COMP & BEN APPS
What I need is for it to show is this:
**<b>APPS SYSTEMS ENGINEER</b> |** TECH & OPS | ENT INFO TECH | DEP & OPS TECH | HR SYS & ITECH | COMP & BEN APPS
Shouldn't it be as simple as:
Position = case coalesce(teamMember.JobTitle, '') when '' then '' else '<b>' + coalesce(teamMember.JobTitle, '') + '</b>' end
+ isnull(' | ' + teamMember.OrganizationNameLevel1, '') --<-- add a Pipe here inside the ISNULL function
+ case when isnull(teamMember.OrganizationNameLevel2, '') <> isnull(teamMember.OrganizationNameLevel1, '') THEN ' | ' + isnull(teamMember.OrganizationNameLevel2, '') ELSE '' END
+ .........

issue with CASE combined with an OR

SELECT
Siren,
CASE WHEN Code_Juridique LIKE 'M%' AND Enseigne IS NOT NULL AND Enseigne <> '' --ok
THEN 'Enseigne : ' + Enseigne
WHEN (Sigle IS NULL OR Sigle ='')
AND (Enseigne IS NULL OR Enseigne ='')
THEN '' -- ok
WHEN
(Sigle IS NOT NULL OR Sigle <> '' ) THEN 'Sigle : ' + Sigle
ELSE 'Sigle / Enseigne : ' + Sigle + ' / ' + Enseigne
END as SigleEnseigne1,
Sigle,
Enseigne,
Code_Juridique
FROM #JohnJack
The code is straightforward.
Issue lies with the third when as you can see below
I should have have nothing on my 4th and 5th line, yet it is giving me Sigle :
What I want is to have the column SigleEnseigne1 on the 4th and 5th line , to be empty
Thanks for your insights
Try this:
SELECT
Siren,
CASE WHEN ( Code_Juridique LIKE 'M%' ) AND ( IsNull( Enseigne, '' ) <> '' )
THEN 'Enseigne : ' + Enseigne
WHEN ( IsNull( RTrim(LTrim(Sigle)), '') = '') AND ( IsNull( Enseigne, '' ) = '')
THEN '' -- ok
WHEN ( IsNull( RTrim(LTrim(Sigle)), '' ) <> '' )
THEN 'Sigle : ' + RTrim(LTrim(Sigle))
ELSE
'Sigle / Enseigne : ' + IsNull( RTrim(LTrim(Sigle)), '' ) + ' / ' + Enseigne
END as SigleEnseigne1,
Sigle,
Enseigne,
Code_Juridique
FROM #JohnJack
Besides stating the obvious that a (TRUE OR FALSE) = TRUE
I would simplify and bullet proof the code by using ISNULL() and LEN().
SELECT
Siren,
CASE WHEN Code_Juridique LIKE 'M%' AND LEN(ISNULL(Enseigne,'')) > 0 --ok
THEN 'Enseigne : ' + Enseigne
WHEN (LEN(ISNULL(Sigle, '')) = 0)
AND (LEN(ISNULL(Enseigne, '')) = 0)
THEN '' -- ok
WHEN
LEN(ISNULL(Sigle, '')) > 0 THEN 'Sigle : ' + Sigle
ELSE 'Sigle / Enseigne : ' + ISNULL(Sigle, '') + ' / ' + ISNULL(Enseigne, '')
END as SigleEnseigne1,
Sigle,
Enseigne,
Code_Juridique
FROM #JohnJack
How would your code react if those fields contain whitespaces? LEN automatically trims trailing whitespaces.
This line is causing your probelm:
(Sigle IS NOT NULL OR Sigle <> '' ) THEN 'Sigle : ' + Sigle
...but that is only obvious because you state that you dont want this result. Other than that the code acts as would be expected.
The simplest solution would be to take out:
'Sigle : ' + Sigle
but that may or may not be precisely what you are looking for. Based on the given information it is the solution but there is not an abundance of information to work off
If you are trying to get non null values to print then it should be an AND rather than an OR. When you use an OR it will return true if EITHER condition is true.
I'm not sure why you have this when
WHEN (Sigle IS NULL OR Sigle = '')
AND (Enseigne IS NULL OR Enseigne ='')
THEN '' -- ok
As what you want is SigleEnseigne1 to be NULL or '' when Sigle is NULL or '' don't you need this when instead
WHEN (Sigle IS NULL OR Sigle = '') THEN ''
There can also be the problem that Sigle is not the empty string and has whitespaces. You can use the LTRIM() and RTRIM() functions
It took me the weekend but actually, I figured out My mistake.
Sorry for the mess
The answer is below
SELECT
Siren,
CASE WHEN ( Code_Juridique LIKE 'M%' ) AND ( IsNull( Enseigne, '' ) <> '' )
THEN 'Enseigne : ' + Enseigne
WHEN ( IsNull( RTrim(LTrim(Sigle)), '') = '') AND ( IsNull( Enseigne, '' ) = '')
THEN '' -- ok
WHEN (Sigle IS NOT NULL OR Sigle <> '') AND (Enseigne IS NULL OR Enseigne = '')
THEN 'Sigle : ' + RTrim(LTrim(Sigle))
WHEN (Sigle IS NULL OR Sigle = '') AND (Enseigne IS NOT NULL OR Enseigne <> '')
THEN ''
WHEN
(Sigle IS NOT NULL OR Sigle <> '') AND (Enseigne IS NOT NULL OR Enseigne <> '')
THEN 'Sigle / Enseigne : ' + IsNull( RTrim(LTrim(Sigle)), '' ) + ' / ' + Enseigne
END as SigleEnseigne1
FROM John_Jack
Have a great end of the year

Why is the field empty when I use a multiple case when?

I have this SQL Code:
SELECT ( P1.Name
+ (CASE P1.Vorname WHEN '' THEN '' ELSE ', ' + P1.Vorname END)
+ (CASE (AP1.Postleitzahl + AP1.Ort)
WHEN '' THEN ''
ELSE ' - ' + (AP1.Postleitzahl + AP1.Ort)
END)
+ (CASE (PKT1.Kennung + PKM1.Kennung)
WHEN ''
THEN
''
ELSE
' - '
+ (CASE PKT1.Kennung
WHEN '' THEN ''
ELSE 'Tel: ' + PKT1.Kennung
END)
+ (CASE PKM1.Kennung
WHEN '' THEN ''
ELSE ' Mobil: ' + PKM1.Kennung
END)
END))
AS [IO1] FROM XYZ
Now when one field is not filled, the cell is empty.
When everything is filled with data the cell gets filled.
So what is the Problem with that code?
I have to work with MSSQL Server 2005 so CONCAT or whatever will not work.
This is your query:
SELECT (P1.Name +
(CASE P1.Vorname WHEN '' THEN '' ELSE ', ' + P1.Vorname END) +
(CASE (AP1.Postleitzahl + AP1.Ort) WHEN '' THEN '' ELSE ' - ' + (AP1.Postleitzahl + AP1.Ort) END) +
(CASE (PKT1.Kennung + PKM1.Kennung) WHEN '' THEN '' ELSE ' - ' + (CASE PKT1.Kennung WHEN '' THEN '' ELSE 'Tel: ' + PKT1.Kennung END) +
(CASE PKM1.Kennung WHEN '' THEN '' ELSE ' Mobil: ' + PKM1.Kennung END) END)
) AS [IO1]
FROM XYZ;
It is going to produce NULL if any of the arguments are NULL. Presumably one or more of the columns is NULL. You can fix this by wrapping things in coalesce() and/or changing the case statements. For instance:
SELECT (coalesce(P1.Name, '') +
(CASE WHEN P1.Vorname = '' or P1.Vorname is null THEN '' ELSE ', ' + P1.Vorname END) +
(CASE WHEN (AP1.Postleitzahl + AP1.Ort) = '' or (AP1.Postleitzahl + AP1.Ort) is null THEN '' ELSE ' - ' + (AP1.Postleitzahl + AP1.Ort) END) +
(CASE WHEN (PKT1.Kennung + PKM1.Kennung) = '' or (PKT1.Kennung + PKM1.Kennung) is null THEN '' ELSE ' - ' + (CASE WHEN PKT1.Kennung = '' or PKT1.Kennung is null THEN '' ELSE 'Tel: ' + PKT1.Kennung END) +
(CASE WHEN PKM1.Kennung = '' or PKM1.Kennung is null THEN '' ELSE ' Mobil: ' + PKM1.Kennung END) END)
) AS [IO1]
FROM XYZ;

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