Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Hi, I have a column in the table defined with the datatype char(1) ....the values that I have in the columns are 6757There are some blank in between. I need to convert this to datatype int .The sql I use :select CASE WHEN column_a = '' THEN 0 ELSE cast(column_a as int) ENDfrom table_aThe error that I get is as follows:Server: Msg 245, Level 16, State 1, Line 1Syntax error converting the varchar value '.' to a column of data type int.I need to convert this column to datatype int with blank values substituted with 0. I ned guidance /help in acheiving this. Please advice.Thank You,dim Dp
Hi tkizer,Could you please help out as to how the syntax will look like if we want to eliminate the period using IsNumeric?Thank You,dimDp
tkizer
Almighty SQL Goddess
38200 Posts
Posted - 2010-08-27 : 17:07:38
I haven't tested it, but maybe something like this would work:select CASE WHEN IsNumeric(column_a) = 0 THEN 0 ELSE cast(column_a as int) ENDfrom table_aIf that doesn't work, try this:select cast(column_a as int) as column_afrom (select column_a = CASE WHEN IsNumeric(column_a) = 0 THEN '0' ELSE column_a END from table_a) dtTara KizerMicrosoft MVP for Windows Server System - SQL Serverhttp://weblogs.sqlteam.com/tarad/Subscribe to my blog
Lamprey
Master Smack Fu Yak Hacker
4614 Posts
Posted - 2010-08-27 : 17:30:31
A small variant of Tara's IsNumeric solution is to use a LIKE:
--Sample DataDECLARE @T TABLE (column_a CHAR(1))INSERT @T (column_a)VALUES ('1'),(' '),('.'),('$'),('%'),('^'),('@'),('3'),('a'),('4'),('5'),('7'),('8'),('-'),('=')SELECT CASE WHEN column_a NOT LIKE '[0-9]' THEN 0 ELSE CAST(column_a AS INT) ENDFROM @T-- ORSELECT CASE WHEN column_a LIKE '[^0-9]' THEN 0 ELSE CAST(column_a AS INT) ENDFROM @T