Click here to Skip to main content
15,890,579 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I use SQL server 2008. There is a field named OTHours and its datatype is varchar.
I have written the following SQL query
Select * from tblSalaryRecordCompliance Where SalarySTDT ='1-Mar-2014' AND CAST(OTHours AS INT)>52
but it arises error. some of the field value like 12, 28:45, 0, -5 etc. where 28:45 means 28 hours and 45 minute
Please help me how can I make a solution of it.
Posted
Updated 26-Apr-14 20:41pm
v2

The best solution is: don't use a varchar field and try and do any maths with it, it only leads to pain. Always use a numeric field for numeric data!

You can do it - SQL has a ISNUMERIC test - but what are you going to do with fields like 28:45? Ignore them? Treat them as matched? Unmatched?
And the ISNUMERIC returns 1 for 123.4 so you still have to play silly buggers even then:
SQL
SELECT * FROM tblSalaryRecordCompliance WHERE SalarySTDT ='1-Mar-2014' AND ISNUMERIC(OTHours) AND CAST(CAST(OTHours AS FLOAT) AS INT)>52


But you would be much, much better off using numeric fields!
 
Share this answer
 
Comments
Sumon562 27-Apr-14 2:36am    
Thanks for your kind response. Here 28:45 means 28 hours 45 minute.
OriginalGriff 27-Apr-14 2:56am    
I did guess that...but if you are going to mix types in your string, then you are always going to get problems - it's a lot, lot easier in the long run to do validation-and-convert when the user enters it, because once it gets into your DB you are stuck with it!
Change the table: use a integer column than hold minutes and convert the user input to that when you store it. Honestly, it reduces your hassle factor by huge amounts later!
SQL
SELECT * FROM tblSalaryRecordCompliance WHERE SalarySTDT ='1-Mar-2014' AND ISNUMERIC(REPLACE(OTHours , ':', '.')) AND CAST(REPLACE(OTHours , ':', '.') AS FLOAT) >52
 
Share this answer
 

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