Table1 has data to be imported into Table2. Table1 contains only varchar fields, but they will be cast to the type of whatever field they are going to be imported into in Table2.
The data has to be imported one row at a time, so I can catch exceptions to find out which rows cause a problem but this doesn’t tell me which column is the culprit and if there are very many exceptions than it’s slower than just checking for valid data ahead of time (not to mention I want the ability to fix problems before starting the import process anyway… preferably without having to actually do a transaction and roll it back just to find out what the issues are).
Ideally, I would like to do something like this:
select RowNumber from table where cast(fieldName as SomeDataType) = 0
Obviously that statement doesn’t make sense because this is not what cast does, but the idea is that I’d like a function that tries to cast the data and returns a true or false value depending on whether the cast was successful.
Is there some easy way to do this that I’ve overlooked?
Related posts:
MS SQL server casting without exception
How do I TryParse in SQL 2000?
You may end up needing to write a user-defined function to that combines a few different methodologies to attempt the cast. Since it’s an import, I’m assuming that performance isn’t the highest concern; calling a UDF will slow down the process.
You could also try writing a CLR stored procedure and use .NET type checking and conversion to at least broadly categorize your data (exact classification may be difficult due to the differences in types between .NET and T-SQL).