DB2- How to check if varchar field value has integers - sql

Is there an inbuilt DB2 function or any query to check if the character i have is a number?
(I cannot use user defined functions)

Doc Link
CASE
WHEN LENGTH(RTRIM(TRANSLATE(test_str, '*', ' 0123456789'))) = 0
THEN 'All digits'
ELSE 'No'
END

if you version of db2 can use regexp_like you can do it:
number with "." as decimal symbol:
select * from yourtable
where REGEXP_LIKE(trim(yourzone) , '^\d+(\.\d*)?$')
number with "," as decimal symbol:
select * from yourtable
where REGEXP_LIKE(trim(yourzone) , '^\d+(\,\d*)?$')
number without decimal symbol ( integer only, your ask)
select * from yourtable
where REGEXP_LIKE(trim(yourzone) , '^\d+$')

There are many approaches. Take a look at that solution using only two functions:
CASE
WHEN REPLACE(TRANSLATE(test_str, '0','123456789','0'),'0','') = ''
THEN 'All digits'
ELSE 'Not all digits'
END
In general - less functions - better performance :)

Use ASCII function to get character value and compare that it is between 48 '0' and 57 '9'
ASCII Table
ASCII Function
Returns the ASCII code value of the leftmost character of the argument as an integer.

The answer by xQbert is not completely correct.
What you actually need is a * for every character in the fromString (and the space needs to be removed) and the length of the to string needs to be the same as the length of the original string.
so it will look like this:
CASE
WHEN LENGTH(RTRIM(TRANSLATE(test_str, '**********', '0123456789'))) = LENGTH(RTRIM(test_str))
THEN 'All digits'
ELSE 'No'
END

Returns numeric where char field is all numerics with no leading or trailing spaces. ie; All characters in the field are numeric:
where translate(char_field, 'X ',' 0123456789') = ' '
Returns non-numeric values with leading spaces considered non-numeric, but trailing spaces ignored. ie; non-numeric if there are leading spaces, but not if there are trailing spaces. This is a common occurrence for mainframe/Cobol-loaded fields:
where not ( length(rtrim(translate(substr(char_field,1,length(rtrim(char_field))),' ','0123456789'))) = 0)
Returns numeric with trailing, but not leading spaces after value. ie; Leading spaces are treated as non-numeric, but trailing spaces are ignored. Again, common for mainframe/Cobol CHAR fields:
where ( length(rtrim(translate(substr(char_field,1,length(rtrim(char_field))),'X ',' 0123456789'))) = 0)
Returns numeric with leading & trailing spaces. ie; ignores leading and trailing spaces in determining field is "numeric":
where ( length(ltrim(rtrim(translate(substr(char_field,1,length(ltrim(rtrim(char_field)))),' ','0123456789')))) = 0)

I have made more error-prone version based on the idea xQbert exposed, added intermedia result, some examples and to_integer column which converts string value safely to integer:
select
test_str
, TRIM(TRANSLATE(replace(trim(test_str), ' ', 'x'), ' ', '0123456789'))
, case when length(TRIM(TRANSLATE(replace(trim(test_str), ' ', 'x'), ' ', '0123456789')))=0
then cast(test_str as int) else null end to_integer
, case when length(TRIM(TRANSLATE(replace(trim(test_str), ' ', 'x'), ' ', '0123456789')))=0
then 'integer' else 'not integer' end is_integer
from (VALUES
(' 123 ' )
,(' abc ' )
,(' a12 ' )
,(' 12 3 ')
,(' 99.3 ')
,('993' )
) AS X(test_str)
;
The result for this example set is:
TEST_STR 2 TO_INTEGER IS_INTEGER
-------- -------- ----------- -----------
123 123 integer
abc abc - not integer
a12 a - not integer
12 3 x - not integer
99.3 . - not integer
993 993 integer

Related

In SQL Server, how can I search for column with 1 or 2 whitespace characters?

So I need to filter column which contains either one, two or three whitespace character.
CREATE TABLE a
(
[col] [char](3) NULL,
)
and some inserts like
INSERT INTO a VALUES (' ',' ', ' ')
How do I get only the row with one white space?
Simply writing
SELECT *
FROM a
WHERE column = ' '
returns all rows irrespective of one or more whitespace character.
Is there a way to escape the space? Or search for specific number of whitespaces in column? Regex?
Use like clause - eg where column like '%[ ]%'
the brackets are important, like clauses provide a very limited version of regex. If its not enough, you can add a regex function written in C# to the DB and use that to check each row, but it won't be indexed and thus will be very slow.
The other alternative, if you need speed, is to look into full text search indexes.
Here is one approach you can take:
DECLARE #data table ( txt varchar(50), val varchar(50) );
INSERT INTO #data VALUES ( 'One Space', ' ' ), ( 'Two Spaces', ' ' ), ( 'Three Spaces', ' ' );
;WITH cte AS (
SELECT
txt,
DATALENGTH ( val ) - ( DATALENGTH ( REPLACE ( val, ' ', '' ) ) ) AS CharCount
FROM #data
)
SELECT * FROM cte WHERE CharCount = 1;
RETURNS
+-----------+-----------+
| txt | CharCount |
+-----------+-----------+
| One Space | 1 |
+-----------+-----------+
You need to use DATALENGTH as LEN ignores trailing blank spaces, but this is a method I have used before.
NOTE:
This example assumes the use of a varchar column.
Trailing spaces are often ignored in string comparisons in SQL Server. They are treated as significant on the LHS of the LIKE though.
To search for values that are exactly one space you can use
select *
from a
where ' ' LIKE col AND col = ' '
/*The second predicate is required in case col contains % or _ and for index seek*/
Note with your example table all the values will be padded out to three characters with trailing spaces anyway though. You would need a variable length datatype (varchar/nvarchar) to avoid this.
The advantage this has over checking value + DATALENGTH is that it is agnostic to how many bytes per character the string is using (dependant on datatype and collation)
DB Fiddle
How to get only rows with one space?
SELECT *
FROM a
WHERE col LIKE SPACE(1) AND col NOT LIKE SPACE(2)
;
Though this will only work for variable length datatypes.
Thanks guys for answering.
So I converted the char(3) column to varchar(3).
This seemed to work for me. It seems sql server has ansi padding that puts three while space in char(3) column for any empty or single space input. So any search or len or replace will take the padded value.

How does Varchar equality work in SQL expressions?

How does varchar equality work in SQL and why? '1' is different from '1 ' actually. See the spaces in the right hand side operand:
SELECT CASE
WHEN '1' = '1 ' THEN 'yes'
ELSE 'no'
END
-- results in yes
The output is 'yes', but why?
This behavior is in accordance with the specs. From a very old version of specs:
3) The comparison of two character strings is determined as follows:
a) If the length in characters of X is not equal to the length in
characters of Y, then the shorter string is effectively replaced, for
the purposes of comparison, with a copy of itself that has been
extended to the length of the longer string by concatenation on the
right of one or more pad characters, where the pad character is chosen
based on CS. [...] Otherwise, the pad character is a <space>.
In plain english, yes, 1 and 1 ​ are compared equal but not 1 and ​ 1.
SQL will ignore all the trailing spaces while comparing your varchar value on =,>,<,>=,<= operators.
if you compare ' 1' and '1' then it give false. But '1 ' and '1' give true.
; with cte as (
SELECT ' 1' as a, '1' as b )
select case when a= b then 'dd' else 'ff' end from cte
Result
--------
ff
; with cte as (
SELECT '1 ' as a, '1' as b )
select case when a= b then 'dd' else 'ff' end from cte
Result
------
dd
It is kind sql internally perform RTRIM by default.
You may find this link for more info LINK
You are comparing two strings. When a string has spaces, it is different.
You can remove all spaces with REPLACE('1 ', ' ', '').
the two string '1' and '1 ' are not equal cause the space ..
for avoid this you should use trim
SELECT CASE
WHEN trim( '1' ) = trim('1 ' ) THEN 'yes'
ELSE 'no'
END

Replacing empty string in SQL using SELECT

I'm trying to replace empty strings with a value and I can't seem to find the best way to do this.
The issue is that SOME values in the phone_number column are in a format without the numbers. For example ( ) -
I want to replace those empty values with 000-0000. I tried to use the CASE WHEN function but that doesn't seem to address the problem. The COALESCE IFNULL won't work because technically the values aren't NULL just incomplete. I'm thinking perhaps the CASE WHEN function would work if I could figure out how to format the empty values correctly.
Here is an example of the code
SELECT
phone_column,
CASE
WHEN phone_column = '() -'
THEN '000-000'
ELSE SUBSTRING(phone_colum, 6, 8)
END AS Phone
FROM
client_table
ORDER BY
linkid_
declare #test table(ph varchar(20))
insert into #test
select '( ) -'
UNION
select ''
UNION
select '(123)-456-7890'
select case
when replace(ph,'( ) -','')='' then '000-000'
else substring(ph,6,8)
end
from #test
if you want to search in a varchar then use LIKE this would help you in using expressions. For instance, in your case phone_column = '() -' would be phone_column LIKE '() -%' this will match any string that begins with () -. if you do phone_column = '() -' then it will only match the exact same string.
Any how, I'm not sure why you want to take this road, while you can validate the current numbers and try to only store the valid ones, as storing invalid numbers would be useless.
I'll give you an example,
to validate phone numbers, you first take out any existed formats (parentheses, dashes, spaces) then you'll be end up with a whole number with 10 or 7 digits. depends on your way of storing phone numbers. any numbers less than that would be invalid.
To remove the formats :
SELECT REPLACE(REPLACE(REPLACE(REPLACE(Number,'(',''),')',''),'-',''),' ','')
Now you will have only numbers, which will be easier to handle.
Like this :
SELECT
phone_column
FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(phone_column,'(',''),')',''),'-',''),' ','') phone_column FROM client_table) D
PS : Some countries phone numbers begins with 0, if your numbers don't
begin with 0, then you would cast the number to BIGINT, which will
remove any leading zeros.
Now, you can use the case to validate the numbers and do whatever you like with them.
SELECT
CASE
WHEN LEN(phone_column) = 10
THEN '(' + SUBSTRING(phone_column,1,3) + ') ' + SUBSTRING(phone_column, 3,3) + '-' + SUBSTRING(phone_column, 6,4)
ELSE '(000) 000-0000'
END Phone
FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(phone_column,'(',''),')',''),'-',''),' ','') phone_column FROM client_table) D

How to remove the begining and ending characters if those are '0' in SQL Server

I currently have a table named DATA it has entries like the following:
abc000
ab000cde
000abc
I just want to remove all 0 from beginning and the end. If 0 comes in between the character then it will remain same.
This also works for leading and trailing zeros at the same time:
declare #s varchar(15) = '00abc00efg000'
select substring(#s,
patindex('%[^0]%', #s),
len(#s)-patindex('%[^0]%', reverse(#s))-patindex('%[^0]%', #s)+2);
Description: this is substring from first nonzero symbol till first nonzero symbol in reversed string.
Say your data exists in column called Col1, then this expression should do it
select CASE
WHEN RIGHT(col1 , 1) = '0'
THEN SUBSTRING(col1,0,PATINDEX('%[A-Z1-9]%',REVERSE(col1)))
WHEN LEFT(col1 , 1) = '0'
THEN SUBSTRING(col1,PATINDEX('%[A-Z1-9]%',col1),LEN(col1))
ELSE
Col1
END AS 'ParsedCol1'
FROM Data
I use this trick:
SELECT
REPLACE(REPLACE(RTRIM(LTRIM(REPLACE(REPLACE(col1, ' ', CHAR(8)), '0', ' '))), ' ', '0'), CHAR(8), ' ')
FROM
yourTable
This may works for SQL, as this removes leading & trailing "000" from your string.
SELECT TRIM(BOTH ‘000’ FROM
‘your_data_table_column’);
See more
http://www.mydigitallife.info/remove-or-trim-first-or-last-few-characters-in-mysql-database-with-sql/
http://www.w3resource.com/mysql/string-functions/mysql-trim-function.php

How can I remove leading and trailing quotes in SQL Server?

I have a table in a SQL Server database with an NTEXT column. This column may contain data that is enclosed with double quotes. When I query for this column, I want to remove these leading and trailing quotes.
For example:
"this is a test message"
should become
this is a test message
I know of the LTRIM and RTRIM functions but these workl only for spaces. Any suggestions on which functions I can use to achieve this.
I have just tested this code in MS SQL 2008 and validated it.
Remove left-most quote:
UPDATE MyTable
SET FieldName = SUBSTRING(FieldName, 2, LEN(FieldName))
WHERE LEFT(FieldName, 1) = '"'
Remove right-most quote: (Revised to avoid error from implicit type conversion to int)
UPDATE MyTable
SET FieldName = SUBSTRING(FieldName, 1, LEN(FieldName)-1)
WHERE RIGHT(FieldName, 1) = '"'
I thought this is a simpler script if you want to remove all quotes
UPDATE Table_Name
SET col_name = REPLACE(col_name, '"', '')
You can simply use the "Replace" function in SQL Server.
like this ::
select REPLACE('this is a test message','"','')
note: second parameter here is "double quotes" inside two single quotes and third parameter is simply a combination of two single quotes. The idea here is to replace the double quotes with a blank.
Very simple and easy to execute !
My solution is to use the difference in the the column values length compared the same column length but with the double quotes replaced with spaces and trimmed in order to calculate the start and length values as parameters in a SUBSTRING function.
The advantage of doing it this way is that you can remove any leading or trailing character even if it occurs multiple times whilst leaving any characters that are contained within the text.
Here is my answer with some test data:
SELECT
x AS before
,SUBSTRING(x
,LEN(x) - (LEN(LTRIM(REPLACE(x, '"', ' ')) + '|') - 1) + 1 --start_pos
,LEN(LTRIM(REPLACE(x, '"', ' '))) --length
) AS after
FROM
(
SELECT 'test' AS x UNION ALL
SELECT '"' AS x UNION ALL
SELECT '"test' AS x UNION ALL
SELECT 'test"' AS x UNION ALL
SELECT '"test"' AS x UNION ALL
SELECT '""test' AS x UNION ALL
SELECT 'test""' AS x UNION ALL
SELECT '""test""' AS x UNION ALL
SELECT '"te"st"' AS x UNION ALL
SELECT 'te"st' AS x
) a
Which produces the following results:
before after
-----------------
test test
"
"test test
test" test
"test" test
""test test
test"" test
""test"" test
"te"st" te"st
te"st te"st
One thing to note that when getting the length I only need to use LTRIM and not LTRIM and RTRIM combined, this is because the LEN function does not count trailing spaces.
I know this is an older question post, but my daughter came to me with the question, and referenced this page as having possible answers. Given that she's hunting an answer for this, it's a safe assumption others might still be as well.
All are great approaches, and as with everything there's about as many way to skin a cat as there are cats to skin.
If you're looking for a left trim and a right trim of a character or string, and your trailing character/string is uniform in length, here's my suggestion:
SELECT SUBSTRING(ColName,VAR, LEN(ColName)-VAR)
Or in this question...
SELECT SUBSTRING('"this is a test message"',2, LEN('"this is a test message"')-2)
With this, you simply adjust the SUBSTRING starting point (2), and LEN position (-2) to whatever value you need to remove from your string.
It's non-iterative and doesn't require explicit case testing and above all it's inline all of which make for a cleaner execution plan.
The following script removes quotation marks only from around the column value if table is called [Messages] and the column is called [Description].
-- If the content is in the form of "anything" (LIKE '"%"')
-- Then take the whole text without the first and last characters
-- (from the 2nd character and the LEN([Description]) - 2th character)
UPDATE [Messages]
SET [Description] = SUBSTRING([Description], 2, LEN([Description]) - 2)
WHERE [Description] LIKE '"%"'
You can use following query which worked for me-
For updating-
UPDATE table SET colName= REPLACE(LTRIM(RTRIM(REPLACE(colName, '"', ''))), '', '"') WHERE...
For selecting-
SELECT REPLACE(LTRIM(RTRIM(REPLACE(colName, '"', ''))), '', '"') FROM TableName
you could replace the quotes with an empty string...
SELECT AllRemoved = REPLACE(CAST(MyColumn AS varchar(max)), '"', ''),
LeadingAndTrailingRemoved = CASE
WHEN MyTest like '"%"' THEN SUBSTRING(Mytest, 2, LEN(CAST(MyTest AS nvarchar(max)))-2)
ELSE MyTest
END
FROM MyTable
Some UDFs for re-usability.
Left Trimming by character (any number)
CREATE FUNCTION [dbo].[LTRIMCHAR] (#Input NVARCHAR(max), #TrimChar CHAR(1) = ',')
RETURNS NVARCHAR(max)
AS
BEGIN
RETURN REPLACE(REPLACE(LTRIM(REPLACE(REPLACE(#Input,' ','¦'), #TrimChar, ' ')), ' ', #TrimChar),'¦',' ')
END
Right Trimming by character (any number)
CREATE FUNCTION [dbo].[RTRIMCHAR] (#Input NVARCHAR(max), #TrimChar CHAR(1) = ',')
RETURNS NVARCHAR(max)
AS
BEGIN
RETURN REPLACE(REPLACE(RTRIM(REPLACE(REPLACE(#Input,' ','¦'), #TrimChar, ' ')), ' ', #TrimChar),'¦',' ')
END
Note the dummy character '¦' (Alt+0166) cannot be present in the data (you may wish to test your input string, first, if unsure or use a different character).
To remove both quotes you could do this
SUBSTRING(fieldName, 2, lEN(fieldName) - 2)
you can either assign or project the resulting value
You can use TRIM('"' FROM '"this "is" a test"') which returns: this "is" a test
CREATE FUNCTION dbo.TRIM(#String VARCHAR(MAX), #Char varchar(5))
RETURNS VARCHAR(MAX)
BEGIN
RETURN SUBSTRING(#String,PATINDEX('%[^' + #Char + ' ]%',#String)
,(DATALENGTH(#String)+2 - (PATINDEX('%[^' + #Char + ' ]%'
,REVERSE(#String)) + PATINDEX('%[^' + #Char + ' ]%',#String)
)))
END
GO
Select dbo.TRIM('"this is a test message"','"')
Reference : http://raresql.com/2013/05/20/sql-server-trim-how-to-remove-leading-and-trailing-charactersspaces-from-string/
I use this:
UPDATE DataImport
SET PRIO =
CASE WHEN LEN(PRIO) < 2
THEN
(CASE PRIO WHEN '""' THEN '' ELSE PRIO END)
ELSE REPLACE(PRIO, '"' + SUBSTRING(PRIO, 2, LEN(PRIO) - 2) + '"',
SUBSTRING(PRIO, 2, LEN(PRIO) - 2))
END
Try this:
SELECT left(right(cast(SampleText as nVarchar),LEN(cast(sampleText as nVarchar))-1),LEN(cast(sampleText as nVarchar))-2)
FROM TableName