I have the following code to cast nvarchar to integer:
cast(@value as int)
However I have no control of the parameter @value, hence the code might fail. Is there anyway to check if a cast is possible before doing a cast?
I have the following code to cast nvarchar to integer:
cast(@value as int)
However I have no control of the parameter @value, hence the code might fail. Is there anyway to check if a cast is possible before doing a cast?
Use a procedure with a TRY CATCH block to suppress errors
i.e.
Now you can call that with the passed string and desired type and the proc returns 1 for success and 0 for failure
Maybe we can do something like this:
I generally use the following, it seems to cover all the situations.
It takes advantage of the fact that "ISNUMERIC" will not allow two periods. The "TRY_CAST" in SQL Server 2012+ is a much better solution though.
The proper test is:
The function
isnumeric()
returns 1 for anything that looks like a float, so you have to be careful.You can also use what I consider to be a peculiarity of SQL Server. You can cast the floating value 1.23 to an int, but you cannot cast the string value. So, the following also works:
Well, in SQL Server 2012 you could use the new TRY_CAST(), but with SQL Server 2008, you should be able to use ISNUMERIC(), and then include handling for values that do not pass that test.
I've recently answered a question about this and using
ISNUMERIC
toCAST
to anINT
won't work by itself. Reason being,ISNUMERIC
returns true for non integer numbers (1.5) for example.Here was a recent answer on the subject:
https://stackoverflow.com/a/14692165/1073631
Consider adding an additional check using CHARINDEX with ISNUMERIC, or what I prefer, use a Regular Expression to validate the data.
And here is a Fiddle demonstrating the problem with using ISNUMERIC on it's own. And the Fiddle using a regular expression instead that works.
Good luck.