Home > Database > Mysql Tutorial > How to Safely Cast Strings to Integers in T-SQL with Default Values or NULL?

How to Safely Cast Strings to Integers in T-SQL with Default Values or NULL?

Patricia Arquette
Release: 2024-12-30 01:51:10
Original
165 people have browsed it

How to Safely Cast Strings to Integers in T-SQL with Default Values or NULL?

TSQL: Casting Strings to Integers with Default Value or NULL

Casting strings to integers is a common task in T-SQL. However, when the conversion is not possible, an error may occur. To handle such situations, T-SQL provides a useful approach that allows you to return a default value or NULL if the conversion fails.

Solution

The solution involves using the ISNUMERIC() function to check if the string can be converted to an integer. If the conversion is possible, the CAST() function is used to convert the string to an integer. Otherwise, a default value or NULL is returned.

The following code snippet demonstrates this approach:

DECLARE @text AS NVARCHAR(10)

SET @text = '100'
SELECT CASE WHEN ISNUMERIC(@text) = 1 THEN CAST(@text AS INT) ELSE NULL END
-- returns 100

SET @text = 'XXX'
SELECT CASE WHEN ISNUMERIC(@text) = 1 THEN CAST(@text AS INT) ELSE NULL END
-- returns NULL
Copy after login

In this example, the first SELECT statement returns 100 because '100' can be converted to an integer. The second SELECT statement returns NULL because 'XXX' cannot be converted to an integer.

Considerations

It's important to note that the ISNUMERIC() function has some limitations. As pointed out by Fedor Hajdu, it may return true for strings containing certain characters, such as $ (currency), , (separators), and -. Therefore, it's recommended to use ISNUMERIC() with caution when validating input for integer conversions.

The above is the detailed content of How to Safely Cast Strings to Integers in T-SQL with Default Values or NULL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template