Remove spaces from right and left (TRIM) all selected columns - sql

I have went through some documentations and as it states SELECT TRIM('') FROM something; can be used to trim strings.
I have SQL command to get the table:
"select NRO,SNAME,NAMEA,NAMEB,ADDRESS,POSTS,POSTN,POSTTP,COMPANY,COUNTRY,BID from COMPANY where ACTIVE = '1' AND NRO Like '7%'"
So I have tried to use:
"select TRIM(NRO),TRIM(SNAME),TRIM(NAMEA),TRIM(NAMEB),TRIM(ADDRESS),TRIM(POSTS),TRIM(POSTN),TRIM(POSTTP),TRIM(COMPANY),TRIM(COUNTRY),TRIM(BID) from COMPANY where ACTIVE = '1' AND NRO Like '7%'"
but this is throwing an error. What is the proper way of using TRIM in this case?
I need to remove spaces from left and right but leave them in between if there are any.
Error message:
Client Interface][LNA][PSQL][SQL Engine]Error in expression: TRIM (
NRO ) ERROR [HY000] [PSQL][ODBC Client Interface][LNA][PSQL][SQL
Engine][Data Record Manager]Invalid user-defined or scalar function.'

You can use LTRIM and RTRIM functions which removes starting and ending spaces for the SQL Server prior to 2017.
So, your query becomes:
select RTRIM(LTRIM(NRO)),
RTRIM(LTRIM(SNAME),
RTRIM(LTRIM(NAMEA)),
RTRIM(LTRIM(NAMEB)),
RTRIM(LTRIM(ADDRESS)),
RTRIM(LTRIM(POSTS)),
RTRIM(LTRIM(POSTN)),
RTRIM(LTRIM(POSTTP)),
RTRIM(LTRIM(COMPANY)),
RTRIM(LTRIM(COUNTRY)),
RTRIM(LTRIM(BID))
from COMPANY where ACTIVE = '1' AND NRO Like '7%'
For the SQL Server 2017 and later you can use TRIM function as Dale K suggested.

Related

Using 'LIKE' in a CASE statement

I am attempting to generate a new field based on an existing field where some of the entries contain different special characters. (ie. *, ') The special characters are at the end of the string, which is either second or third position.
I am NEW to SQL but not new to data. I am using a CASE WHEN statement. I have tried several approaches and several other commands within the CASE statement.
what I want is:
SELECT *
CASE WHEN grde_code_mid LIKE '[*]' THEN 'Remedial'
WHEN grde_code_mid LIKE '[']' THEN 'Continuing'
ELSE NULL
END AS class_type
FROM grde_tble
I keep getting the same error: "FROM keyword not found where expected". I expect to have all 3 returns in the new field.
If you're looking for ' character you should escape it.
Change
WHEN grde_code_mid LIKE '[']' THEN 'Continuing'
by
WHEN grde_code_mid LIKE '['']' THEN 'Continuing'
Have a look at this question: How do I escape a single quote in SQL Server?
There are several issues with your query:
you are missing a comma in the SELECT clause between * and the CASE expression (this is causing the error that you are currently getting)
the bracket notations is only supported in SQL-Server; if you want to match on strings that end with * in a portable manner, you need expression ... LIKE '%*', not LIKE '[*]'
single quotes embedded in a string need to be escaped
SELECT *, other_field FROM ... is not supported on all RDBMS (and, as commented by jarhl, actually isn't standard ANSI SQL notation); you usually need to prefix the * with the table name or alias
Consider:
SELECT
g.*,
CASE
WHEN grde_code_mid LIKE '%*' THEN 'Remedial'
WHEN grde_code_mid LIKE '%''' THEN 'Continuing'
ELSE NULL
END AS class_type
FROM grde_tble g
Thank you all. I am still getting the hang of the language and proper terms. I am using Oracle DB. Also, yes, I did need to reference the table in the select statement (SELECT tablename.*). Found a work around:
CASE WHEN regexp_like(grde_code_mid, '[*]') THEN 'Remedial'
WHEN regexp_like(grde_code_mid, '['']') THEN 'Continuing'
ELSE NULL END AS special_class

split string with character

using SQL 2008; I have the following string:
EMCo: 1 WorkOrder: 12770 WOItem: 10
I am trying to get the WorkOrder #.
When the string did not have the WOItem on end of it, I was able to use the following statement to get WorkOrder #.
[WorkOrder] = LTRIM(RTRIM(RIGHT(HQMA.KeyString,CHARINDEX(':',REVERSE(HQMA.KeyString))-1)))
This statement moves and may have double digits for the Co#, and it does not always have WOItem #. Was hoping to find something that would split after the ":" and just take 2nd group.
Any suggestions?
The patindex suggestion above will work beautifully, now if you still want to use your current statement, substring will pull the same values, and replace will take out WOItem. Not very elegant, it works whether you have WOItem or not:
select substring(LTRIM(RTRIM(RIGHT(REPLACE(HQMA.KeyString,'WOItem:',''),
CHARINDEX(':',REVERSE(REPLACE(HQMA.KeyString,'WOItem:','')))-1))),0,7)
select substring(LTRIM(RTRIM(RIGHT(REPLACE(HQMA.KeyString,'WOItem:',''),
CHARINDEX(':',REVERSE(REPLACE(HQMA.KeyString,'WOItem:','')))-1))),0,7)
How about using patindex()? Assuming the work order always has five characters:
select substring(HQMA.KeyString,
patindex('%WorkOrder: %', HQMA.KeyString) + 11,
5) as WorkOrder

Escaping a single quote in Oracle regex query

This is really starting to hurt!
I'm attempting to write a query in Oracle developer using a regex condition
My objective is to find all last names that contain charachters not commonly contained in names (non-alpha, spaces, hyphens and single quotes)
i.e.
I need to find
J00ls
McDonald "Macca"
Smithy (Smith)
and NOT find
Smith
Mckenzie-Smith
El Hassan
O'Dowd
My present query is
select * from dm_name
WHERE regexp_like(last_name, '([^A-Za-z -])')
and batch_id = 'ATEST';
which excludes everything expected except the single quote. When it comes to putting the single quote character, the Oracvel SQL Develoepr parser takes it as a literal.
I've tried:
\' -- but got a "missing right parenthesis" error
||chr(39)|| -- but the search returned nothing
'' -- negated the previous character in the matching group e.g. '([^A-Za-z -''])' made names with '-' return.
I'd appreciate anything you could offer.
Just double the single quote to escape your quote.
So
select *
from dm_name
where regexp_like(last_name, '[^A-Za-z ''-]')
and batch_id = 'ATEST'
See also this sqlfiddle. Note, I tried a similar query in SQL developer and that worked as well as the fiddle.
Note also, for this to work the - character has to be the last character in the group as otherwise it tries to find the group SPACE to ' rather than the character -.
The following works:
select *
from dm_name
WHERE regexp_like(last_name, '([^A-Za-z ''-])');
See this SQLFiddle.
Whether SQL Developer will like it or not is something I cannot attest to as I don't have that product installed.
Share and enjoy.

Select query that displays Joined words separately, not using a function

I require a select query that adds a space to the data based on the placement of the capital letters i.e. 'HelpMe' using this query would be displayed as 'Help Me' . Note i cannot use a stored function to do this the it must be done in the query itself. The Data is of variable length and query must be in SQL. Any Help will be appreciated.
Thanks
You need to use user defined function for this until MS give us support for regular expressions. Solution would be something like:
SELECT col1, dbo.RegExReplace(col1, '([A-Z])',' \1') FROM Table
Aldo this would produce leading space that you can remove with TRIM.
Replace regular expresion function:
http://connect.microsoft.com/SQLServer/feedback/details/378520
About dbo.RegexReplace you can read at:
TSQL Replace all non a-z/A-Z characters with an empty string
Assume if you are using Oracle RDBMS, you use the following,
REGEX_REPLACE
SELECT REGEXP_REPLACE('ILikeToWatchCSIMiami',
'([A-Z.])', ' \1')
AS RX_REPLACE
FROM dual
;
Managed to get this output: * SQLFIDDLE
But as you see it doesn't treat well on words such as CSI though.

How do I modify these group of functions to get everything left of #?

I have a column that has values stored in the following format:
name#URL
All data is stored with this and a second # is never present.
I've got the following statement that strips the URL from this column:
SELECT SUBSTRING ( wf_name ,PATINDEX ( '%#%' , wf_name )+1 , LEN(wf_name)-(PATINDEX ( '%#%' , wf_name )) )
However I want to take the name also (everything left of the #). Unfortuantely I don't understand the functions I'm using above (having read the documentation I'm still confused). Could somebody please help me to understand the flow and how I can adjust this to get everything left of #?
Have a look at the following example
; WITH Table1 AS (
SELECT 'TADA#TEST' AS NameURL
)
SELECT *,
LEFT(NameURL,PATINDEX('%#%',NameURL) - 1) LeftText,
RIGHT(NameURL,PATINDEX('%#%',NameURL)- 1) RightText
FROM Table1
SQL Fiddle DEMO
Using functions
PATINDEX (Transact-SQL)
Returns the starting position of the first occurrence of a pattern in
a specified expression, or zeros if the pattern is not found, on all
valid text and character data types.
LEFT (Transact-SQL)
Returns the left part of a character string with the specified number
of characters.
RIGHT (Transact-SQL)
Returns the right part of a character string with the specified number
of characters.