Trim SQL field and use ISNULL - sql

fairly new to SQL and having problems with trimming the data when using in an ISNULL statement
LTRIM(RTRIM(CA.CUSTNMBR)) as AccountNumber
The above gives me the account number without spaces (correct)
,ISNULL(NAN.SageAccountNo, LTRIM(RTRIM(CA.CUSTNMBR))) AS AccountNumber
I then tried to use the same principle in the above ISNULL statement but it returns the correct column but doesn't trim the data.

I think you want:
LTRIM(RTRIM(COALESCE(NAN.SageAccountNo, CA.CUSTNMBR))) as AccountNumber
This will trim either SageAccountNo or CUSTNMBR.

You just need to use LTRIM(RTRIM( outside the ISNULL:
LTRIM(RTRIM(ISNULL(NAN.SageAccountNo, CA.CUSTNMBR)))

Related

verify function SAS to sql

I have a verify function in SAS in a select query as below. May I know how to convert that in SQL to use in pyspark.
select substr(upercase(strip(emp)),verify(strip(emp),"0")) as id from Emp_table.
VERIFY(target-expression, search–expression)
The VERIFY function returns the position of the first character in target-expression that is not present in search-expression. If there are no characters in target-expression that are unique from those in search-expression, VERIFY returns a 0.
Your search-expression is a single character 0 so the processing that is occurring is selecting the emp value without its leading zeroes.
Looks like you want to ltrim with expression trim(LEADING '0' ...

LTRIM(RTRIM(COLUMN)) in sql server

I need to create a query to collect all the rows with column A not null and not blank.
When I used this:
AND A.EXP_GRAD_TERM is not null AND A.EXP_GRAD_TERM <> ' '
I got 1169 records which all have some values for the field.
But when I used this:
AND LTRIM(RTRIM(A.EXP_GRAD_TERM)) is not null
I got 1932 records. They have the rows with values and rows with blanks. I even convert the column, the column only has blanks or the values, not other weird invisible character.
I do not know why. I thought they should have worked the same way.
Any thoughts?
This expression:
LTRIM(RTRIM(A.EXP_GRAD_TERM)) is not null
is exactly equivalent to:
A.EXP_GRAD_TERM is not null
An empty string is different from NULL, so removing spaces -- even from a string that only has spaces -- has no effect on the NULL comparison.
If you are confused, perhaps you have experience with Oracle where empty strings and NULL are the same thing. That is a peculiar property of Oracle.
LTRIM() function:
Returns a character expression after it removes leading blanks.
RTRIM() function:
Returns a character string after truncating all trailing spaces.
They are different from IsNull or empty string condition (CASE WHEN IS NULL OR <>'')
References
LTRIM (Transact-SQL)
RTRIM (Transact-SQL)
Combine COALESCE() with LTRIM() and RTRIM():
AND RTRIM(LTRIM(COALESCE(A.EXP_GRAD_TERM, ''))) <> ''
COALESCE(A.EXP_GRAD_TERM, '') will return '' for every null value.
see if you want to get the values that are not null and not empty you can use isnull (exp, replace_value)
AND RTRIM(LTRIM(ISNULL(A.EXP_GRAD_TERM, ''))) <> ''
isnull isnull replaces a null value for which you want to replace it. you could also use COALESCE which "returns the first non-null expression among your arguments"
One apparent advantage that COALESCE has over ISNULL is that it supports more than two inputs, whereas ISNULL supports only two. Another advantage of COALESCE is that it's a standard function (namely, defined by the ISO/ANSI SQL standards), whereas ISNULL is T-SQL–specific. These differences between the two functions are fairly straightforward.
if you want more information about the differences between ISNULL and COALESCE you can see it on this link

How to use regex replace in Postgres function?

I have postgres function in which i am appending values in query such that i have,
DECLARE
clause text = '';
after appending i have some thing like,
clause = "and name='john' and age='24' and location ='New York';"
I append above in where clause of the query i already have. While executing query i am getting "and" just after "where" result in error
How to use regex_replace so that i remove the first "and" from clause before appending it to the query ?
Instead of fixing clause after the fact, you could avoid the problem by using
concat_ws (concatenate with separator):
clause = concat_ws(' and ', "name='john'", "age='24'", "location ='New York'")
will make clause equal to
"name='john' and age='24' and location ='New York'"
This can be even simpler. Use right() with a negative offset.
Truncates the first n characters and you don't need to specify the length of the string. Faster, simpler.
Double quotes (") are for identifiers in Postgres (and standard SQL) and incorrect in your example. Enclose string literals in single quotes (') and escape single quotes within - or use dollar quoting:
Insert text with single quotes in PostgreSQL
Since this is a plpgsql assignment, use the proper assignment operator :=. The SQL assignment operator = is tolerated, too, but can lead to ambiguity in corner cases.
Finally, you can assign a variable in plpgsql at declaration time. Assignments in plpgsql are still cheap but more expensive than in other programming languages.
DECLARE
clause text := right($$and name='john' and age='24' ... $$, -5)
All that said, it seems like you are trying to work with dynamic SQL and starting off on the wrong foot here. If those values can change, rather supply them as values with the USING clause of EXECUTE and be wary of SQL injection. Read some of the related questions and answers on the matter:
https://stackoverflow.com/search?q=[plpgsql]+[dynamic-sql]+EXECUTE+USING
You do not need regex:
clause = substr(clause, 5, 10000);
clause = substr(clause, 5, length(clause)- 4); -- version for formalists
concat_ws sounds like the best option, but as a general solution for things like this (or any sort of list with a delimiter) you can use logic like (pseudocode):
delim = '';
while (more appendages)
clause = delim + nextAppendage;
delim = ' AND ';
If you want to do it with regular expression try this:
result = regexp_replace(clause, '^and ', '')

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.

SQL Query: data with comma

Im using sql server 2005. i want data with comma. for example ['5000'],['5001'],..
but the last record should not include comma. Pls help me.
Query:
select '['''+convert(varchar,parcelid)+'''],' from sampletable
Try the COALESCE function
SELECT #groupedText = COALESCE(#groupedText, '') + [Text] + ','
FROM Requirement
WHERE CampaignId = #campaignId
ORDER BY [Text]
Then you could try one of the string functions to kill the end comma
T-SQL string functions
You can use regular expressions to remove the last comma or do it using your programming language (ASP etc. like a chop function or something).
http://weblogs.sqlteam.com/jeffs/archive/2007/04/27/SQL-2005-Regular-Expression-Replace.aspx
Consider using XML for this purpose. The "aggregate concatenation" solution may not be reliable, because it is not clearly documented and supported. You can get rid of the final comma with SUBSTRING, as boon suggested.
See this thread.