Click here to Skip to main content
15,879,326 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I wonder if we have any way (query) to convert data types right in SQL commands?
For example, converting a string to an integer. Before converting, I may want to check if the conversion is possible, how can I check it, of course right in SQL commands?

Note: suppose that the field has no constraint of CHECK!
Thank you so much!
Posted

you can write like this--
SQL
declare @var1 as char(20)
set @var1="214"

select case when isnumeric(@var1) =1 then cast(@var1 as float) else null end 

or you can directly put the value

select case when isnumeric(col1) =1 then cast(col1 as float) else null end from tablename
select case when isnumeric('525') =1 then 525 else null end 


for access the query will change as

select iif(isnumeric(col1) ,cdbl(col1),null) from tablename


and the syntex is-
SQL
Case when condition then truepart else falsepart end
iif(condition,truepart,falsepart)

--Pankaj
 
Share this answer
 
v3
Comments
[no name] 17-Apr-11 8:35am    
Thank you!
Could you please tell me more about:
1. The syntax of select with case, every key words in it.
2. How can I declare a variable by using OleDbCommand?
I intend to execute all queries in programming environment with C#, not in the query designer window of ms access or the query analyzer window of sql server.
Thank you so much!
pankajupadhyay29 18-Apr-11 0:40am    
I write the query according to your question, you need not to declare any variable you can replace your column with variable or directly write the values there.

Thanks
pankajupadhyay29 18-Apr-11 0:47am    
the solution is edited as your question and you can directly use these queries in OleDb command from C#.
To determine the data type for a column you can query INFORMATION_SCHEMA.COLUMNS. For example:
SELECT * from INFORMATION_SCHEMA.COLUMNS

Using that information, you can create a small function which casts the column for another data type (based on parameters).
 
Share this answer
 
Comments
[no name] 17-Apr-11 8:29am    
Thank you!
Does Information_schema.columns exist in ms access database? And if not, is there the same table in access?
Because I'm using a ms access database.
Thank you so much!
Wendelius 17-Apr-11 10:46am    
For Access I'm not aware of existence of similar views. I guess that using TableDef you could obtain the same information. See: http://msdn.microsoft.com/en-us/library/bb220949.aspx
[no name] 17-Apr-11 13:57pm    
OK! Your answer will be accepted! Please wait! Look at the solution 1, I have asked him more about his answer and am waiting for a reply from him.
Thank you!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900