Get Max +1 of VarChar Column - sql

I have a table which contains both text and numbers in a varchar column called EMPLOYEE_CODE. I want to ignore all the text and get the Highest number in the Column and then + 1 which i can then assign to a new employee. The code below would work on an INT Column but not on the VARCHAR because of the text i get the below error:
Conversion failed when converting the varchar value 'testusercode' to
data type int.
SELECT MAX(EMPLOYEE_CODE) + 1 as Target
FROM [COMPANY].[dbo].[USER]
WHERE EMPLOYEE_CODE + 1 NOT IN (SELECT EMPLOYEE_CODE From dbo.USER)
I am guessing I have to add convert or cast to the query but not sure how

You can use ISNUMERIC to check for number, get maximum value and add 1.
SELECT MAX(EMPLOYEE_CODE) + 1 as Target
FROM [COMPANY].[dbo].[USER]
WHERE ISNUMERIC(EMPLOYEE_CODE) = 1
If you are using newer versions of SQL Server, you can also use
SELECT MAX(EMPLOYEE_CODE) + 1 as Target
FROM [COMPANY].[dbo].[USER] WHERE TRY_PARSE(EMPLOYEE_CODE AS int) IS NOT NULL
There are TRY_CAST and TRY_CONVERT also for same stuff. You can easily check which one suits your purpose.
https://learn.microsoft.com/en-us/sql/t-sql/functions/try-cast-transact-sql

Related

Converting nvarchar to int, converting phone with symbols with only numbers

I am trying to convert phone number from the column 'phone' from the table 'Clients'. I have tried the following syntaxes, but I still get error messages -
1. SELECT CAST(phone as int)
FROM Clients
Error: Conversion failed when converting the nvarchar value '030-3456789' to data type int
2. SELECT CONVERT(int, phone)
FROM Clients
Conversion failed when converting the nvarchar value '030-3456789' to data type int.
3. SELECT CAST(phone AS BIGINT)
FROM Clients
WHERE ISNUMERIC(phone) = 1
The query doesn't return error but there is no result, the column is empty.
It looks (from your example syntax) like you might be using SQL Server.
If that's the case and it's 2017+ you can do the following which copes with any combination of non-numeric values.
Based on your comments the following should work
select Try_Convert(bigint, Replace(Translate('(5) 789-0123','()-',' '),' ',''))
Result: 57890123
If you are using SQL Server 2016 or earlier you have to nest multiple replacements:
select Try_Convert(bigint, Replace(Replace(Replace(Replace('(5) 789-0123)','-',''),'(',''),')',''),' ',''))
Because at least some of your records cannot be covert to numeric by default, as the indicated one 030-3456789
You basically need to replace/eliminate the dash in between:
SELECT cast(replace('12-3', '-', '') as int)
Anyway, welcome to StackOverflow.

Numeric comparison of a varchar column to a decimal column

I have the following tables
productinfo:
ID|productname|productarea|productcost|productid
sales:
ID|salesid|productid|
salesdata:
ID|productid|productname|salestotal
Where I am having trouble is: salesdata.salestotal is a varchar column and may have nulls
Comparing the salesdata.saletotal to the productinfo.productcost columns.
I can do a
cast(salesdata.saletotal as float(7)) > X
and it works. I would like to do is
cast(salesdata.saletotal as float(7)) > productinfo.productcost
where
sales.productid = salesdata.productid and
productinfo.productid = salesdata.productid
However when I do that I get an error:
Error when converting type varchar to float
I found this post which was similar but am unable to get any other columns with it. I can not change the current db structure.
You can add a IsNumeric() to your where clause to check that salesdata.saletotal can be parsed to float
SELECT
cast(salesdata.saletotal as float(7)) > productinfo.productcost
FROM Sales,Salesdata
WHERE
sales.productid = salesdata.productid and
productinfo.productid = salesdata.productid and
IsNumeric(salesdata.saletotal) =1
Or you can use Not Like (best than IsNumeric)
salesdata.saletotal NOT LIKE '%[^0-9]%'
if you are using sql server version 2012 and above, you can use try_cast() or try_parse()
try_cast(salesdata.saletotal as float)>productinfo.productcost
or
try_parse(salesdata.saletotal as float)>productinfo.productcost
Prior to 2012, I would use patindex('%[^0-9.-]%',salesdata.saletotal)=0 to determine if something is numeric, because isnumeric() is somewhat broken.
e.g. rextester: http://rextester.com/UZE48454
case when patindex('%[^0-9.-]%',salesdata.saletotal)>0
then null
when isnull(cast(salesdata.saletotal as float(7)),0.0)
> isnull(cast(productinfo.productcost as float(7)),0)
then 1
else 0
end

Retrieve Numeric Value out of String SQL

I have a column Property in a table Order. We used to store a dictionary(varchar) in this column.
We now have a new column (int) called ShoeSize which has a default value of 0.
So what I want to achieve is to retrieve only the numeric value out of the Property column and update the ShoeSize column with that value.
The Property column value looks like this:
ShoeSize<|$à&£#>15<|#ç§~#>
or
ShoeSize<|$à&£#>3<|#ç§~#>
My question is:
How can I manipulate my SQL in select statement to select only the numeric value of the Property column? So in other words, How would I be able to only end up with 15 or 3
Thanks in advance.
If you are using MSSQL and your format is fixed then you can try like below
DECLARE #str VARCHAR(50)
SET #str = 'ShoeSize<|$à&£#>15<|#ç§~#>'
SELECT SUBSTRING(#str,CHARINDEX('£#>',#str) + 3, CHARINDEX('<|#',#str) - (CHARINDEX('£#>',#str) + 3))
You can use REGEXP_SUBSTR to extract the numbers from your string.
For example,
SELECT REGEXP_SUBSTR('ShoeSize<|$à&£#>15<|#ç§~#>','[[:digit:]]+') FROM dual;
will return 15 to you. Of course, my assumption is that the shoe size in your string will be a number, and your intention is not to collate all digits which occur in your string to come at a number which you will save as shoe size

how to convert different datatypes to int in sql

I have a nvarchar(200) column in a table that contains a mix of integers (as strings) and non-integer strings and symbols also. E.g. Some sample data :-
Excuse me for my typing in my initial post I mentioned varchar(200) but in fact it is 'nvarchar(200)'
02
0
.../
125
00125
/2009
1000
0002589
000.00125
Marathi numbers like & letters
how can I order this Column?
You can use CAST to convert a varchar to an INT given that varchar is holding a proper number.
SELECT CAST(varCharCol as Int)
E.g.
col1 as Varchar(10)
col1 = '100' converting to INT will be successufl
but if col1 = '100 xyz' will be unsucessful in the process.
Looking at your string you may have to use number of LTRIM, REPLACE to get hold of the digits or using a regex to get comma separated numbers. That too it's not very clear how your original string looks like.
References.
Many DBMS have CAST() functions where you can convert one datatype to another.
For MySQL have a look at this site
You can Use CAST and Convert to convert string type value to int type. but be sure the value should numeric.
select convert(int,'123')
select CAST('123' as int)
You can use this query
SELECT CASE
WHEN ISNUMERIC(colName)=1 THEN ROUND(colName, 0)
ELSE 0 END AS [colName]
FROM tblName

determine DB2 text string length

I am trying to find out how to write an SQL statement that will grab fields where the string is not 12 characters long. I only want to grab the string if they are 10 characters.
What function can do this in DB2?
I figured it would be something like this, but I can't find anything on it.
select * from table where not length(fieldName, 12)
From similar question DB2 - find and compare the lentgh of the value in a table field - add RTRIM since LENGTH will return length of column definition. This should be correct:
select * from table where length(RTRIM(fieldName))=10
UPDATE 27.5.2019: maybe on older db2 versions the LENGTH function returned the length of column definition. On db2 10.5 I have tried the function and it returns data length, not column definition length:
select fieldname
, length(fieldName) len_only
, length(RTRIM(fieldName)) len_rtrim
from (values (cast('1234567890 ' as varchar(30)) ))
as tab(fieldName)
FIELDNAME LEN_ONLY LEN_RTRIM
------------------------------ ----------- -----------
1234567890 12 10
One can test this by using this term:
where length(fieldName)!=length(rtrim(fieldName))
This will grab records with strings (in the fieldName column) that are 10 characters long:
select * from table where length(fieldName)=10
Mostly we write below statement
select * from table where length(ltrim(rtrim(field)))=10;