Basically I want to do this:
I want to return a record set converting one nvarchar value (ID) to an integer if it contains a number. If ID can be converted to a number, then add that row to the SELECT
record set. If not, skip that row.
I think the SQL should look something like this.
(ID is nvarchar(10) in dbo.Table)
CREATE TABLE #Temp (ID int)
INSERT INTO #Temp SELECT ID FROM Table Where ISNumeric(Id)=0
But I get an error: nvarchar value 'Default' to data type int. If I do a SELECT CAST(ID as int)
that does not work either.
In SQL Server, we can use the ISNUMERIC() function to return numeric values from a column. We can alternatively run a separate query to return all values that contain numeric data.
The ISNUMERIC() function tests whether an expression is numeric. This function returns 1 if the expression is numeric, otherwise it returns 0.
To be safe, forget about ISNUMERIC
If you are not expecting negative numbers, you can use this
INSERT INTO #Temp SELECT ID FROM Table
Where Id > '' -- is not the empty string and is not null
AND not ID like '%[^0-9]%' -- contains digits only
ISNumeric(Id)=0
should be ISNumeric(Id)=1
However ISNUMERIC has a problem
run this
SELECT ISNUMERIC('2d5'), ISNUMERIC('-'), ISNUMERIC('+')
Those all return 1
Take a look at IsNumeric, IsInt, IsNumber for some ways to figure out if it can be converted to an integer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With