This question already has answers here:
Check if a string contains only number
(5 answers)
Detect if value is number in MySQL
(15 answers)
Closed 5 months ago.
The community reviewed whether to reopen this question 5 months ago and left it closed:
Original close reason(s) were not resolved
I have a variable declared as nvarchar in the SP, its value is dynamic, it can be a string or a number, its value comes from the UI when user writes in the global search textbox to search a table. I need to cast its value from a string to a decimal only when the value is a number, however, I'm getting error when casting because the cast() returns error when casting a string like 'abc' but works fine if the value is '2000'.
How to check if the value is castable or not?
SELECT CAST('abc' AS DECIMAL(7,2) ) -- retruns error Error converting data type varchar to numeric.
SELECT CAST('2.0000' AS DECIMAL(7,2) ) -- retruns 2.00
You tagged this mysql, but MySQL does not raise an error when you try to cast a non-numeric string to a number. It returns 0 in that case (which I consider a design flaw in this DBMS).
The error message you are showing suggests another DBMS, most likely Microsoft SQL Server.
In SQL Server use TRY_CAST, which returns null if the string is not numeric:
SELECT *
FROM mytable
WHERE numcol = TRY_CAST(#searchstring AS DECIMAL(7,2));
The above query returns no rows if the string contains a non-numeric value. If you want to return all rows instead:
SELECT *
FROM mytable
WHERE numcol = TRY_CAST(#searchstring AS DECIMAL(7,2))
OR TRY_CAST(#searchstring AS DECIMAL(7,2)) IS NULL;
Docs: https://learn.microsoft.com/en-us/sql/t-sql/functions/try-cast-transact-sql?view=sql-server-ver16
Related
This question already has answers here:
Can't convert varchar values to data type int
(2 answers)
Closed 9 months ago.
SELECT CONVERT([int],11.25)-CONVERT([int],'10.25')
How to avoid error and return 1 as result.
This is not a duplicate question. The similar question you referred is complex when comparing to my simple query question.
Rather than using the implicit behaviour of the CONVERT function, why not use the correct function, e.g. ROUND
SELECT ROUND(11.25, 0)-ROUND(CONVERT(DECIMAL(9,2),'10.25'), 0)
This question already has answers here:
Conversion to datetime fails only on WHERE clause?
(6 answers)
Conversion failed when converting from a character string to uniqueidentifier error in SQL Server
(4 answers)
Closed 6 years ago.
I have been hitting a strange issue lately on SQL Server.
The application I am using is saving user's attributes in a table containing user/attribute/value records. I need to find whether a user is still valid using his end of validity date. The query I have been using is the following:
SELECT COUNT(*) FROM value_all
WHERE AttrName = 'VALIDTO' AND
userkey=574924 AND
CONVERT (DATE,Value, 120) < GETDATE();
The conversion is necessary because all values are stored as VARCHAR.
The query was working correctly but lately I have been hitting the following error:
SQL Error [241] [S0001]: Conversion failed when converting date and/or time from character string.
I though that the stored validity date was wrong. However, the value does match the correct format:
SELECT * FROM value_all
WHERE AttrName = 'VALIDTO' AND
userkey=574924 AND
|userkey |AttrName |Value |
|--------|-----------|--------------------|
|574924 |VALIDTO |2016-07-31T23:59:59 |
I can even do a convert and show the result correctly:
SELECT CONVERT (DATE,Value, 120) AS Date FROM value_all
WHERE AttrName = 'VALIDTO' AND
userkey=574924 AND
CONVERT (DATE,Value, 120) < GETDATE();
|Date |
|-----------|
|2016-07-31 |
However, as soon as I add the COUNT, the error is coming back.
Does any-one have an idea of what is going on in this case? Is it linked, in some way, to the value used?
EDIT
Thanks to the question at "Conversion to datetime fails only on WHERE clause?", I was able to rework my query as follow, which correct the issues I had:
SELECT COUNT(*) FROM value_all
WHERE AttrName = 'VALIDTO' AND
userkey=574924 AND
CONVERT (DATE, CASE WHEN ISDATE(Value) THEN Value END, 120) < GETDATE();
The answer is that there is no guarantee of the order in which the WHERE clause operates. It looks like it may be applying the Convert of the value field before it filters the rows on userkey or attrName. Most likely the count is causing the plan to change which is just an unlucky side effect.
You chould retrieve the row with the userkey and attrname and then convert the value.
Curious, is there an index on the userkey field? And on attrname?
This question already has answers here:
How to convert float to varchar in SQL Server
(15 answers)
Closed 8 years ago.
I am trying a number column to varchar in SQL select statement. It is returning in exponential value. How can I get as it is in string
Select CAST([Loan Number] as nVARCHAR(50)) as strLoanNumber
From
[tbl_DS] Where [Loan] like '%CWALT_2006%'
Actual value is 127160640
Returning value is 1.27161e+008
Try using
convert(nvarchar(50),[loan number])
This question already has answers here:
CAST and IsNumeric
(11 answers)
Closed 8 years ago.
Why does the following Query in SQL return true??
I expected it to be false as it cannot be converted into an int or numeric value
select ISNUMERIC(',')
return 1???
select ISNUMERIC('0,1,2')
select ISNUMERIC(',,,')
also returns 1
What could I do for strict numeric checking in SQL?
Because ISNUMERIC answers a question that nobody has ever wanted to ask:
Can this given string be converted into any of SQL Server's numeric data types? And I don't care which of those types it can or cannot be converted into.
This is why TRY_CONVERT was finally introduced into 2012 - to answer a question about a specific data type that you may care about.
For earlier versions, the best you can usually do is to use LIKE to identify the string patterns you do want to attempt to convert.
E.g. if you just want to detect digits, use Value NOT LIKE '%[^0-9]%', which asks for Value strings that do not contain any character which is not a digit.
IsNumeric returns true for "," and "."
ISNUMERIC returns 1 if the string can be converted to any one of ints, numeric/decimal, float, or money. In this particular case, converting ',.' to money succeeds and returns 0.0000, therefore ISNUMERIC returns 1.
Enhancement to ISNUMERIC:
We have now added a new scalar function called TRY_CONVERT that will allow you to convert from a string to type using optional style. If the conversion fails then it will return NULL. The signature of the function is:
TRY_CONVERT(data_type[(length)], expression [,style])
http://msdn.microsoft.com/en-us/library/ms186272.aspx
Microsoft: "It's not a bug, it's a feature "
Certain currency and mathematic symbols return 1 on ISNUMERIC.
As per the manual page:
ISNUMERIC returns 1 for some characters that are not numbers, such as plus (+), minus (-), and valid currency symbols such as the dollar sign ($). Also, it returns 1 for a range of datatypes like:
int
bigint
smallint
tinyint
decimal
So while bigint accepts money values like 230,000, a comma(,) also falls in the set of character which is considered to be a part of a numeric datatype similar to a dot(.) which is a character but is a part of the decimal datatype.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Convert DB2 SQL Decimal to DATE
I have a db2 database and I want to convert a decimal to a date during the where clause in a select statement.
The decimal date could be 12 or 13 characters long depending on the month.
12 characters:
1,241,999.00 should become: 1999/1/24
13 Characters:
12,241,999.00 should become: 1999/12/24
The column name is DECIMALCOLUMN:
Select * from table1 WHERE
cast(replace(convert,DECIMALCOLUMN,date)) = #date
I see: You want some way of rearranging the digits of a number to become a date. It looks like the encoding is [m]mddyyyy. (Why isn't that a date datatype in the database?)
The number needs to be converted to a string and then substrings arranged and converted to a date. Given the complexities here, a conversion function should be written in lieu of the field being altered to be a proper datatype. Something like this should do it (untested, no access to db2):
create function decimaldate(decdate DECIMAL)
returns DATE
return
with tmp (dstr) as
(
select substr(digits (decdate),8)
from sysibm.sysdummy1
)
select
date (substr(dstr,4,4) || '-' ||
substr(dstr,1,2) || '-' ||
substr(dstr,3,2)
)
from tmp
This converts the number to a string, reformats the string as yyyy-mm-dd and converts to a date. (I used this as a basis.)
So the solution to the original question is simply to write:
SELECT *
FROM table1
WHERE decimaldate(DECIMALCOLUMN) = #date
With such a screwy way of encoding the date in the database, having the function always available should prove invaluable.