Leading zero using sql server - sql

I need to add leading zero in my records, but it doesn't work then I have no idea to solve this. the data as follow
textmess
convert
8
08
8
008
14
014
this is the query i have run
Select right('000' + rtrim(ltrim(cast(TEXTMESS as varchar(3)))), 3) convert, TEXTMESS from mytable
I thought it would work but it didn't work for first row, it should be 008 right? why the result is different with second row? . please help to solve this query

You can go for FORMAT and apply preceding 0.
DECLARE #table table(textmess int)
insert into #table
values (8),(8),(14)
SELECT textmess, FORMAT(textmess,'000') as convertedTExt from #table
textmess
convertedTExt
8
008
8
008
14
014

It seems that you have a special non-visible character in that row. First check that varchar value in hex to check which character code is it:
Select
right('000' + rtrim(ltrim(cast(TEXTMESS as varchar(3)))), 3) AS Converted,
TEXTMESS,
CONVERT(VARBINARY, TEXTMESS) AS HexValues
from
mytable
Seems that for a row you have 0x38 and for the other 0x381C. Assuming that the values are in ASCII, 38 is the 8 and 1C is the hex for symbol FS (file separator).
If you check any ASCII table online, you can see that the code for FS is 28, so just use REPLACE with CHAR(28). Check the result first:
Select
right('000' + rtrim(ltrim(cast(TEXTMESS as varchar(3)))), 3) AS Converted,
TEXTMESS,
REPLACE(TEXTMESS, CHAR(28), '') AS Replaced,
right('000' + rtrim(ltrim(cast(REPLACE(TEXTMESS, CHAR(28), '') as varchar(3)))), 3) AS ReplacedConverted
from
mytable
Then remove the character with UPDATE for all rows that have any FS:
UPDATE T SET
TEXTMESS = REPLACE(TEXTMESS, CHAR(28), '')
FROM
mytable AS T
WHERE
CHARINDEX(CHAR(28), TEXTMESS) > 0

try this
SELECT RIGHT('000'+CAST(textmess AS VARCHAR(3)),3)convertedText, textmess from mytable

Related

Insert values append with zero with charcter length 5

I have a serial no column in my table. I want to insert values like this:
00001
00002
.........
00010
00011
........
00100
How can I write a query for this?
Since you are trying to store a number and padding with leading zero wont mean anything.
But while displaying you can pad it with leading zero and select number of digit you want using RIGHT() function
SELECT RIGHT('00000' + CAST([serial_number] AS varchar(5)) , 5)
FROM [Table_name]

SQL - Changing data type of an alphanumeric column

I'm on Teradata. I have an ID column that looks like this:
23
34
W7
007
021
90
GS8
I want to convert the numbers to numeric so the 007 should be 7 and 021 be 21. When a number is stored as a string, I usually do column * 1 to convert to numeric but in this case it gives me a bad character error since there are letters in there.
How would I do this in a select statement within a query?
Assuming that numeric values always start with a number, then something like this should work:
update t
set col = (case when substr(col, 1, 1) between '0' and '9'
then cast(cast(col as int) as varchar(255))
else col
end);
Or, you can forget the conversion and do:
update t
set col = trim(leading '0' from col);
Note: both of these assume that if the first character is a digit then the whole string comprises digits. The second assumes that the values are not all zeroes (or, more specifically, that returns the empty string).
Simply use TO_NUMBER(col) which returns NULL when the cast fails.

UPDATE multiple values in table t-sql

I have multiple columns where one of them has varchar values as follow.
1
2
4
02
05
6
03
06
123
32
87
I want to find any record that has values starting with 0 > remove that 0 (so 02 > 2) and update that field so there is no value starting with 0.
How can I go about doing that instead of manually updating each record that has 0 in the front? Is that even possible?
Thank you
The following code removes the leading zeros by casting the value to an integer and back to a character string:
update t
set col = cast(cast(col as int) as varchar(255))
where t.col like '0%'
You can use the following:
update yourtable
set col = substring(col, 2, len(col)-1)
where left(col, 1) = '0'
See SQL Fiddle with Demo
Run this query until everything is filtered out I guess...
UPDATE Table SET Column=RIGHT(Column, LEN(Column)-1) WHERE Column LIKE '0%';
[Edit] Gordon's approach is probably better.

Select Part of Column

I was wondering if anyone could help with a query to select part of a column.
The column 'criteriadata' contains data that would look like this:
CriteriaData
14 27 15 C
14 30 15 DD
14 38 15 Pass
14 33 15 Pass
How can I select just the data that appears after the number 15.
Many thanks.
SELECT RIGHT(CriteriaData,
LEN(CriteriaData) - CHARINDEX('15', CriteriaData, 1) - 2)
FROM TableName
WHERE CriteriaData LIKE '%15%';
SQL Fiddle Demo
declare #T table
(
CriteriaData varchar(20)
)
insert into #T values
('14 27 15 C'),
('14 30 15 DD'),
('14 38 15 Pass'),
('14 33 15 Pass')
select stuff(CriteriaData, 1, 3+charindex(' 15 ', CriteriaData), '')
from #T
Result:
---------
C
DD
Pass
Pass
If CriteriaCData always contains a pattern of 3 numbers of 2 numerics separated by a space then you always want to retrieve from 10th chars:
select SUBSTR(CriteriaCData, 10) from xxx
If you are under oracle min 10.g then use REGEXP_SUBSTR to retrieve the alpha pattern
SELECT upper(REGEXP_SUBSTR(CriteriaCData, '[a-zA-Z]*$')) FROM xxx
Since you seem to want everything from the ninth character onwards, you could use RIGHT and LEN
SELECT right([CriteriaData], len([CriteriaData]) - 9)
However, you'd be better off normalizing your data so it was already in a seperate column.
On oracle use LENGTH instead of LEN
SELECT substr(CriteriaData, 8, LENGTH(CriteriaData) - 9) from table
You should use substring with left functions
Have a look at this: How to extract this specific substring in SQL Server?
And this: http://msdn.microsoft.com/en-us/library/aa259342(v=sql.80).aspx
SELECT substring(criteriadata, 9, LEN(criteriadata)-8) from table
This assumes that the position of 15 is fixed.
Declare #x nvarchar(100) = '14 30 15 DD';
Select substring(#x, (select charindex('15',#x,1) + 2) ,len(#x));
I created a SQL function to split the criteria by the spaces and used the last remaining value after the last space.
create function dbo.getCriteria
(
#criteria varchar(500)
)
returns varchar(500)
begin
declare #space as int
select #space=charindex(' ', data) from mydata
while #space > 0
begin
set #criteria=substring(#criteria, #space + 1, len(#criteria))
select #space=charindex(' ', #criteria)
end
return #criteria
end
select dbo.getCriteria(data) from mydata
SELECT
RIGHT(CriteriaData, LEN(CriteriaData) - (CHARINDEX('15', CriteriaData, 1) - 2))
FROM
MyTable;
As I had trouble making prior answers work, I had to find my own and figure for future reference I'd leave it on Stack Overflow. My field has XML but it's an NVarchar field and should generalise just fine - if you have a clear criteria for left AND right surrounding strings.
It's not a complete match to this question but I hope it helps someone else who has huge strings in their columns and needs to snip out a string that varies in between two others!
WITH r
AS (
SELECT TOP 100 RIGHT(XMLData, LEN(XMLData)-CHARINDEX('<INVOICE_NO>', XMLData)-11) AS xmldata
FROM IncomingPartsInvoiceXML)
SELECT LEFT(xmldata, CHARINDEX('<\/INVOICE_NO>', XMLData)-1)
FROM r;

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.