TSQL CASE WHEN THEN SYNTAX - USING REPLACE - sql

This actually applies to a prior question, TSQL 2008 USING LTRIM(RTRIM and Still Have Spaces
I am at the point of writing a very lengthy SELECT statement using OMG PONIES statement to remove NON NULL non visible characters
(WHEN PropStreetAddr is NOT NULL THEN
(SELECT LTRIM(RTRIM((REPLACE(PropStreetAddr,
SUBSTRING(PropStreetAddr,
PATINDEX('%[^a-zA-Z0-9 '''''']%',
PropStreetAddr),
1), '') AS PropStreetAddr)
Query:
SELECT
CASE WHEN LOAN_NUMBER IS NOT NULL THEN
REPLACE( LOAN_NUMBER,SUBSTRING (LOAN_NUMBER,PATINDEX( ' %[^a-zA-Z0-9 '''''']% ' , ' ' ) as LOAN_NUMBER.
,CASE WHEN MERS_ID IS NOT NULL THEN
REPLACE( MERS_ID,SUBSTRING (MERS_ID,PATINDEX( ' %[^a-zA-Z0-9 '''''']% ' , ' ' ) as MERS_ID
...127 more lines of similar statements
As soon as I check the syntax I receive this error pointing to the first Case statement after SELECT:
Msg 156, Level 15, State 1, Line 143
Incorrect syntax near the keyword 'as'.
Could someone help me understand what I am missing?

You're missing the END from your case statements. You look like you could do with ELSEs in there as well, although these are not compulsory - if left off and nothing matches then you'll get a NULL.
CASE
WHEN something then value1
WHEN somethingelse then value2
ELSE value3
END

You are missing some right parrens.

Related

TRIM forward slash in T-SQL

I have the following code...
TRIM(LEADING '/' FROM ci.Long_description_1) as 'Description',
I am getting the error message
Incorrect syntax near '/'
Whats the best way of writing this?
Thanks
If you are using SQL Server 2017+, you may use TRIM() with a small trick (by default TRIM() removes the specified characters from the start and the end of the string):
SELECT LEFT(
TRIM('/' FROM Long_description_1 + '?'),
LEN(TRIM('/' FROM Long_description_1 + '?')) - 1
) AS Description
FROM (VALUES
(NULL),
('abcd'),
('1234/'),
('////abcd'),
('/folder/subfolder/x.yz')
) ci (Long_description_1)
Result:
Description
----------------------
abcd
1234/
abcd
folder/subfolder/x.yz
I think you want to remove '/' if it is the first character of Long_description_1 column value. TRIM function in SQL Server will not work the way you are expecting.
For this you can write your query like following.
SELECT CASE
WHEN CHARINDEX('/', ci.Long_description_1) = 1
THEN RIGHT(ci.Long_description_1, LEN(ci.Long_description_1) - 1)
ELSE ci.Long_description_1
END AS [Description]
FROM YouTable

Using IF condition inside CONCAT function of SQL Query

I am trying to implement a concatenation inside a SQL query. I need to use comma as separator between the values.
select concat(technology,',',secondary_technology,',',tertiary_technology) as Technology from deals
This works completely fine. But if there are no values in secondary and tertiary technology columns, the result looks something like
Blue Prism,,
So I need to put a condition if secondary and tertiary technologies are null, then the commas need to be omitted.
I am using the following query:
select concat(technology,if(secondary_technology is null,'',','),secondary_technology,if(tertiary_technology is null,'',','),tertiary_technology) as Technology from deals
But this throws error saying
Incorrect Syntax near the keyword 'if'.
Incorrect Syntax near ','.
Please help me with this!
I am using MS SQL Server 2014
Thank you in advance..
Concat will ignore NULL values when appending. Try this
select CONCAT(technology, ',' +secondary_technology, ',' +tertiary_technology)
from deals
If technology column could be null.
select case when technology is null then stuff(Result, 1, 1, '') else Result end
from (
select technology, CONCAT(technology, ',' +secondary_technology, ',' +tertiary_technology) as Result
from deals
) tab
You might also want to check for Empty string columns using NULLIF.
select case
when coalesce(technology,'') = '' then stuff(Result, 1, 1, '')
else Result
end Result
from
(
select technology
, CONCAT(technology, ',' + nullif(secondary_technology,''), ',' + nullif(tertiary_technology,'')) as Result
from deals
) tab
Use coalesce() :
select concat(technology, coalesce(',' +secondary_technology, ''), coalesce(',' +tertiary_technology, '')) as Technology
from deals;
EDIT : Use stuff() :
select stuff(<concat query> 1,1, '')
from deals;
Please use the below code as alternative:
SELECT CONCAT(technology, ISNULL(secondary_technology,''),ISNULL(tertiary_technology,'')) AS Technology
FROM deals;
try this:
select concat(
technology,
CASE WHEN secondary_technology IS NOT NULL
THEN concat(', ', secondary_technology)
ELSE ''
END,
CASE WHEN tertiary_technology IS NOT NULL
THEN concat(', ', tertiary_technology)
ELSE ''
END,
) as Technology
from deals;
See this answer related to this issue: https://stackoverflow.com/a/19242830/3554534

Issue with replacing negative values with zero

Checked similar threads but no similar issues were experienced by other users.
The code does not seem to work and the error message says "Unexpected token 'Then' at line 11".
Lines 6 to 8 get the calculated column that determines the savings but if it is a loss, it becomes negative. I wanted to replace all negative values with 0 using Case but for some reason 'then' is treated as an error.
Select Distinct Reports.rptviewGovtTransparencyCode.project_title As Title,
Reports.rptviewContract.AwardedDateTime As Awarded,
Reports.rptviewContract.estimated_value As Budget,
Convert(decimal,Replace(Reports.rptviewCustomFieldAnswer.Answer, ',',
'')) As Value,
Reports.rptviewContract.estimated_value -
Convert(decimal,Replace(Reports.rptviewCustomFieldAnswer.Answer, ',',
'')) As Saving,
case when (Reports.rptviewContract.estimated_value -
Convert(decimal,Replace(Reports.rptviewCustomFieldAnswer.Answer, ',', ''))
<= 0 then 0) As Saving2
From Reports.rptviewGovtTransparencyCode
Inner Join Reports.rptviewContract On Reports.rptviewContract.contract_id =
Reports.rptviewGovtTransparencyCode.contract_id
Inner Join Reports.rptviewCustomField On Reports.rptviewCustomField.OrgId =
Reports.rptviewContract.OrgId
Inner Join Reports.rptviewCustomFieldAnswer
On Reports.rptviewCustomFieldAnswer.TargetAreaId =
Reports.rptviewContract.project_id And Reports.rptviewCustomField.Id =
Reports.rptviewCustomFieldAnswer.CustomFieldId
Inner Join Reports.rptviewContractPrimaryContact
On Reports.rptviewContract.contract_id =
Reports.rptviewContractPrimaryContact.ContractId
Where Reports.rptviewGovtTransparencyCode.department = '1capital' And
Reports.rptviewCustomField.Title = 'awarded value'
This:
case when (Reports.rptviewContract.estimated_value -
Convert(decimal,Replace(Reports.rptviewCustomFieldAnswer.Answer, ',', ''))
<= 0 then 0)
is missing the case's end, and also has a wrong parenthesis couple enclosing both the coondition and the "then" after the when clause. Replace it with the following:
case when Reports.rptviewContract.estimated_value -
Convert(decimal,Replace(Reports.rptviewCustomFieldAnswer.Answer, ',', ''))
<= 0 then 0 end
In order to demonstrate better, what you had before was:
case when (condition then result)
while the correct was
case when condition then result end
You shall not p...hide the "then" inside the parenthesis: the "when" cannot see it.

Running SQL query to remove all trailing and beginning double quotes only affects first record in result set

I'm having a problem when running the below query - it seems to ONLY affect the very first record. The query removes all trailing and beginning double quotes. The first query is the one that does this; the second query is just to demonstrate that there are multiple records that have beginning double quotes that I need removed.
QUESTION: As you can see the first record resulting from the top query is fine - it has its double quotes removed from the beginning. But all subsequent queries appear to be untouched. Why?
If quotes are always assumed to exist at both the beginning and the end, adjust your CASE statement to look for instances where both cases exist:
CASE
WHEN ([Message] LIKE '"%' AND [Message] LIKE '%"') THEN LEFT(RIGHT([Message], LEN([Message])-1),LEN([Message]-2)
ELSE [Message]
EDIT
If assumption is not valid, combine above syntax with your existing CASE logic:
CASE
WHEN ([Message] LIKE '"%' AND [Message] LIKE '%"') THEN LEFT(RIGHT([Message],LEN([Message])-1),LEN([Message]-2)
WHEN ([Message] LIKE '"%') THEN RIGHT([Message],LEN([Message]-1)
WHEN ([Message] LIKE '%"') THEN LEFT([Message],LEN([Message]-1)
ELSE [Message]
Because your CASE statement is only evaluating the first condition met, it will only ever remove one of the statements.
Try something like the following:
SELECT REPLACE(SUBSTRING(Message, 1, 1), '"', '') + SUBSTRING(Message, 2, LEN(Message) - 2) + REPLACE(SUBSTRING(Message, LEN(Message), 1), '"', '')
EDIT: As Martin Smith pointed out, my original code wouldn't work if a string was under two characters, so ...
CREATE TABLE #Message (Message VARCHAR(20))
INSERT INTO #Message (Message)
SELECT '"SomeText"'
UNION
SELECT '"SomeText'
UNION
SELECT 'SomeText"'
UNION
SELECT 'S'
SELECT
CASE
WHEN LEN(Message) >=2
THEN REPLACE(SUBSTRING(Message, 1, 1), '"', '') + SUBSTRING(Message, 2, LEN(Message) - 2) + REPLACE(SUBSTRING(Message, LEN(Message), 1), '"', '')
ELSE Message
END AS Message
FROM #Message
DROP TABLE #Message
Try this:
SELECT REPLACE([Message], '"', '') AS [Message] FROM SomeTable

TSQL CASE LTRIM (RTRIM NULL

SQL Syntax is still something I am learning. I am getting the error noted below the this snippet of code.
SELECT
CASE WHEN LTRIM(RTRIM(cLehmanNo)) =' ' THEN NULL
WHEN cLehmanNo IS NOT NULL THEN REPLACE ( cLehmanNo,SUBSTRING (cLehmanNo,PATINDEX( '%[^a-zA-Z0-9 '''''']%',cLehmanNo),1), ' ' )
END asLOAN_NUMBER
,CASE WHEN LTRIM(RTRIM(cMERS)) =' ' THEN NULL
WHEN cMERS IS NOT NULL THEN REPLACE ( cMERS,SUBSTRING (cMERS,PATINDEX( '%[^a-zA-Z0-9 '''''']%',cMERS),1), ' ' )
END asMERS_ID
and 100+ more of same.
Msg 8133, Level 16, State 1, Line 1
None of the result expressions in a CASE specification can be NULL.
What am I doing wrong? How do I keep the gist of the statement and not get this crazy error?
This happens when it can't infer the type.
e.g.
SELECT CASE WHEN 1 = 2 THEN NULL ELSE NULL END
But this works
SELECT CASE WHEN 1 = 2 THEN NULL ELSE replace(NULL,'','') END
so I doubt the error is from the code you have shown us (You are using string functions and the following quick test shows that it will assume that to be varchar(8000))
SELECT CASE WHEN 1 = 2 THEN NULL ELSE REPLACE(NULL,'','') END a
INTO t /*Creates column of datatype varchar(8000)*/
You need to convert NULL to a correct type matching the overall values, e.g. CONVERT(VARCHAR(10), NULL), otherwise the server can't deduce which type to make the resulting value.
The error message actually means that all results in one of your case expressions are null. You have an expression like:
case when something then null when something then null end
At least one of the results has to be something other than null. You could circumvent this, but most likely there is a mistake in the query, as a case exression that always returns the same result is pointless.
The error message has been changed to:
At least one of the result expressions
in a CASE specification must be an
expression other than the NULL
constant.
SELECT
CASE WHEN LTRIM(RTRIM(cLehmanNo)) =' ' THEN NULL
WHEN cLehmanNo IS NOT NULL THEN REPLACE ( cLehmanNo,SUBSTRING (cLehmanNo,PATINDEX( '%[^a-zA-Z0-9 '''''']%',cLehmanNo),1), ' ' )
ELSE ''
END asLOAN_NUMBER
,CASE WHEN LTRIM(RTRIM(cMERS)) =' ' THEN NULL
WHEN cMERS IS NOT NULL THEN REPLACE ( cMERS,SUBSTRING (cMERS,PATINDEX( '%[^a-zA-Z0-9 '''''']%',cMERS),1), ' ' )
ELSE ''
END asMERS_ID