Space handling in Teradata - sql

I have the following rows in the table
Record_Value
E1X4B1 20160822
E1XBA1 20160822
E1 X920160822
I need to select the values X4,XB and X9. I wrote the query :
SELECT SUBSTR(Record_Value,3,2)
It selects only X4 and XB. To select the value X9 (which is in the 7th position) I thought of using the coalesce function but it handles only NULL values and not BLANK values. Can you please guide me. Expected Output would be
X4
XB
X9

A different solution simply removes all spaces before the substring:
SUBSTRING(OTRANSLATE(Record_value,' ','') FROM 3 FOR 2)

Use TRIM to remove the leading blanks (and trailing...):
SELECT SUBSTR(TRIM(Record_Value),1,2)
Answer number 2, to the edited question, ANSI SQL compliant:
SELECT SUBSTRING(TRIM(SUBSTRING(Record_Value FROM 3)) FROM 1 FOR 2)

Related

How to choose output length based on whether or not first character is a letter?

I am trying to return a column in sql
which should return 4 characters from the column when the character starts with an alphabet, for a numeric it should return only 3 characters .
Eg:
column:
B98497
C68756
r45789
123467
578912
output:
the above column should return the following
column:
B984
C687
r457
123
578
I used the following code but it returns only first three characters
my code:
select substring(column,1,3)
from table
the output for my code:
column
B98
C68
r45
123
578
how do I get an output like this:
B984
C687
r457
123
578
One method is:
select left(col, 3 + (col rlike '^[a-zA-Z'))
This uses the fact that boolean expressions evaluate to 1 or 0 in a number context.
If you already use MySQL 8.0, there's a one-liner:
SELECT REGEXP_SUBSTR(column1, '[a-z]?[0-9]{3}') FROM Table1;
Demo. And here's the corresponding docpage.
If it's 5.7, you have to check the first symbol against letter character class, like this:
SELECT LEFT(column1, IF(column1 RLIKE '^[a-z]', 4, 3)) FROM Table1;
... which can actually be simplified as showed in #GordonLinoff answer.
Demo.
Following Should Do
select
CASE WHEN substring(TheColumn, 1,1) LIKE '[0-9]' THEN substring(TheColumn, 1,3)
ELSE substring(TheColumn, 1, 4) END
from [dbo].[TabAlpNum]

get last _ position values in sql server

Hi I have one doubt in sql server .
how to get first position to right side specific character position.
table : empfiles
filename:
ab_re_uk_u_20101001
ax_by_us_19991001
abc_20181002
I want output like below:
filename
ab_re_uk_u
ax_by_us
abc
I tried like below :
select SUBSTRING(filename,1,CHARINDEX('2',filename) - 1) as filename from empfiles
above query is not given expected result please tell me how to write query to achive this task in sql server .
If last position has always numeric values then you can use patindex():
select *, substring(filename, 1, patindex('%[0-9]%', filename)-2) as NewFile
from empfiles e;
If you want to get characters after than _ to right sight of string then you can use combo to reverse() and substring()
select *,
reverse(substring(reverse(filename),charindex('_', reverse(filename))+1, len(filename)))
from empfiles e;
Another way is to use reverse in combination with STUFF.
create table f(filename nvarchar(100));
insert into f values
('ab_re_uk_u_20101001')
,('ax_by_us_19991001')
,('abc_20181002');
select
filename=reverse(stuff(reverse(filename),1,charindex('_',reverse(filename)),''))
from f
Try This
CREATE TABLE #DATA([FILENAME] NVARCHAR(100));
INSERT INTO #DATA VALUES
('ab_re_uk_u_20101001')
,('ax_by_us_19991001')
,('abc_20181002');
SELECT [filename],
SUBSTRING([filename],0,PATINDEX('%[0-9]%',[filename])-1) AS ExpectedResult
FROM #Data
Result
filename ExpectedResult
--------------------------------------
ab_re_uk_u_20101001 ab_re_uk_u
ax_by_us_19991001 ax_by_us
abc_20181002 abc
Well, obviously the last position value is a date, and the format is YYYYMMDD so its 8 characters, plus, added by underscore character, so that makes its 9 character.
Assumed by the above statement applied, the following logic of the query should work
SELECT SUBSTRING(ColumnText, 1, LEN(ColumnText) - 9)
Which means, only display characters from character position 1, to character position LEN - 9, which LEN is the length of characters, and 9 is the last 9 digit of number to be removed
Try with this ..
select [filename],SUBSTRING([filename],1,PATINDEX('%_[0-9]%',[filename])-1) from empfiles
Individual Select records
SELECT SUBSTRING('ab_re_uk_u_20101001',1,PATINDEX('%_[0-9]%','ab_re_uk_u_20101001')-1)
SELECT SUBSTRING('ax_by_us_19991001',1,PATINDEX('%_[0-9]%','ax_by_us_19991001')-1)
SELECT SUBSTRING('abc_20181002',1,PATINDEX('%_[0-9]%','abc_20181002')-1)

Insert into sql Max +1 only numbers (prevent characters)

I'm using this code
(SELECT (MAX(CODE) +1 WHERE ISNUMERIC([code]) = 1)
I want to max +1 only my numbers of my column preventing characters characters.
NOTE: THIS QUESTION WAS TAGGED MYSQL WHEN THIS ANSWER WAS POSTED.
You can use substring_index() to split the values and then re-unite them:
(SELECT CONCAT(SUBSTRING_INDEX(MAX(Code), '-', 1), '-',
SUBSTRING_INDEX(MAX(CODE), '-', -1) + 1
)
FROM . . .
WHERE code LIKE '%NEW-1%'
)
This assumes that the wildcards do not have hyphens in them, and that the values after the "1" are all numbers.
Also, this doesn't pad the number is zeroes, but that is a good idea for such codes -- it ensures that they are always the same length and that they sort correctly.
The MAX() function accepts expressions, not just column names:
SELECT MAX(CASE ISNUMERIC(code) WHEN 1 THEN code END)+1 as next_code
FROM (
SELECT '15' AS code
UNION ALL SELECT ' 98 ' AS code
UNION ALL SELECT 'New-45' AS code
) foo
WHERE ISNUMERIC(code)=1;
16
(Link is to SQL Server 2005, docs for SQL Server 2000 are apparently no longer on line, but MAX() belongs to SQL standard anyway.)

Remove leading zeros

Given data in a column which look like this:
00001 00
00026 00
I need to use SQL to remove anything after the space and all leading zeros from the values so that the final output will be:
1
26
How can I best do this?
Btw I'm using DB2
This was tested on DB2 for Linux/Unix/Windows and z/OS.
You can use the LOCATE() function in DB2 to find the character position of the first space in a string, and then send that to SUBSTR() as the end location (minus one) to get only the first number of the string. Casting to INT will get rid of the leading zeros, but if you need it in string form, you can CAST again to CHAR.
SELECT CAST(SUBSTR(col, 1, LOCATE(' ', col) - 1) AS INT)
FROM tab
In DB2 (Express-C 9.7.5) you can use the SQL standard TRIM() function:
db2 => CREATE TABLE tbl (vc VARCHAR(64))
DB20000I The SQL command completed successfully.
db2 => INSERT INTO tbl (vc) VALUES ('00001 00'), ('00026 00')
DB20000I The SQL command completed successfully.
db2 => SELECT TRIM(TRIM('0' FROM vc)) AS trimmed FROM tbl
TRIMMED
----------------------------------------------------------------
1
26
2 record(s) selected.
The inner TRIM() removes leading and trailing zero characters, while the outer trim removes spaces.
This worked for me on the AS400 DB2.
The "L" stands for Leading.
You can also use "T" for Trailing.
I am assuming the field type is currently VARCHAR, do you need to store things other than INTs?
If the field type was INT, they would be removed automatically.
Alternatively, to select the values:
SELECT (CAST(CAST Col1 AS int) AS varchar) AS Col1
I found this thread for some reason and find it odd that no one actually answered the question. It seems that the goal is to return a left adjusted field:
SELECT
TRIM(L '0' FROM SUBSTR(trim(col) || ' ',1,LOCATE(' ',trim(col) || ' ') - 1))
FROM tab
One option is implicit casting: SELECT SUBSTR(column, 1, 5) + 0 AS column_as_number ...
That assumes that the structure is nnnnn nn, ie exactly 5 characters, a space and two more characters.
Explicit casting, ie SUBSTR(column,1,5)::INT is also a possibility, but exact syntax depends on the RDBMS in question.
Use the following to achieve this when the space location is variable, or even when it's fixed and you want to make a more robust query (in case it moves later):
SELECT CAST(SUBSTR(LTRIM('00123 45'), 1, CASE WHEN LOCATE(' ', LTRIM('00123 45')) <= 1 THEN LEN('00123 45') ELSE LOCATE(' ', LTRIM('00123 45')) - 1 END) AS BIGINT)
If you know the column will always contain a blank space after the start:
SELECT CAST(LOCATE(LTRIM('00123 45'), 1, LOCATE(' ', LTRIM('00123 45')) - 1) AS BIGINT)
both of these result in:
123
so your query would
SELECT CAST(SUBSTR(LTRIM(myCol1), 1, CASE WHEN LOCATE(' ', LTRIM(myCol1)) <= 1 THEN LEN(myCol1) ELSE LOCATE(' ', LTRIM(myCol1)) - 1 END) AS BIGINT)
FROM myTable1
This removes any content after the first space character (ignoring leading spaces), and then converts the remainder to a 64bit integer which will then remove all leading zeroes.
If you want to keep all the numbers and just remove the leading zeroes and any spaces you can use:
SELECT CAST(REPLACE('00123 45', ' ', '') AS BIGINT)
While my answer might seem quite verbose compared to simply SELECT CAST(SUBSTR(myCol1, 1, 5) AS BIGINT) FROM myTable1 but it allows for the space character to not always be there, situations where the myCol1 value is not of the form nnnnn nn if the string is nn nn then the convert to int will fail.
Remember to be careful if you use the TRIM function to remove the leading zeroes, and actually in all situations you will need to test your code with data like 00120 00 and see if it returns 12 instead of the correct value of 120.

T-SQL Substring - Last 3 Characters

Using T-SQL, how would I go about getting the last 3 characters of a varchar column?
So the column text is IDS_ENUM_Change_262147_190 and I need 190
SELECT RIGHT(column, 3)
That's all you need.
You can also do LEFT() in the same way.
Bear in mind if you are using this in a WHERE clause that the RIGHT() can't use any indexes.
You can use either way:
SELECT RIGHT(RTRIM(columnName), 3)
OR
SELECT SUBSTRING(columnName, LEN(columnName)-2, 3)
Because more ways to think about it are always good:
select reverse(substring(reverse(columnName), 1, 3))
declare #newdata varchar(30)
set #newdata='IDS_ENUM_Change_262147_190'
select REVERSE(substring(reverse(#newdata),0,charindex('_',reverse(#newdata))))
=== Explanation ===
I found it easier to read written like this:
SELECT
REVERSE( --4.
SUBSTRING( -- 3.
REVERSE(<field_name>),
0,
CHARINDEX( -- 2.
'<your char of choice>',
REVERSE(<field_name>) -- 1.
)
)
)
FROM
<table_name>
Reverse the text
Look for the first occurrence of a specif char (i.e. first occurrence FROM END of text). Gets the index of this char
Looks at the reversed text again. searches from index 0 to index of your char. This gives the string you are looking for, but in reverse
Reversed the reversed string to give you your desired substring
if you want to specifically find strings which ends with desired characters then this would help you...
select * from tablename where col_name like '%190'