Convert column value to int in SQL Server -
i working on query , returning exception cannot convert varchar
int
:
select bg_priority, count(*) cnt bug bg_target_rel= case when isnumeric('xxxx 13.5') = 1 cast('xxxx 13.5' int) else 'xxxx 13.5' end group bg_priority
this query generated c# code. clause filter can numeric or string 1 user chooses type of filter he/she wants , according gives value.
is there approach can add type of filter in query?
if column types int
, varchar
, can use this:
select bg_priority, count(*) cnt bug <chosencolumn> = 'inputvalue' group bg_priority;
this works using sql server's implicit data type precedence conversions. if int, input value, '123'
converted number 123 (exactly want!). if column varchar, quoted value remains varchar.
your original cast error stems fact case statement results in 1 datatype , 1 only, using same data type precedence rules linked above. consider branches:
case when isnumeric('xxxx 13.5') = 1 cast('xxxx 13.5' int) --<< branch returns int else 'xxxx 13.5' --<< branch returns varchar end >> data type precedence ==> resultant type of expression "int"
when give value 'xxxx 13.5', case statement results in 'xxxx 13.5', needs cast case expression resultant type
, i.e. int => fail.
Comments
Post a Comment