Is there any way to check whether some string compatible with some MS SQL type?
I’m going to validate strings before inserting it into tables in database.
EDIT: I’m looking for a method to check if some string is compatible with varchar, char, bit, etc…
If I’m interpreting this correctly, you have input as strings that you want to store in a SQL Server database, and the columns will be different types, like
int,float, andmoney. You want to know if the strings will convert to the appropriate type successfully.One way would be to simply pass the strings in as parameters to a
SqlCommandusing a parameterized query, setting the appropriate SQL data types for your parameters. When you execute the command with data that won’t convert, you’ll getFormatExceptions.More explicitly, you could try to parse your strings with the appropriate SQL data type. If the conversion fails, it will also throw a
FormatException.Even if you parse the strings, I would still recommend using a parameterized SQL query with
SqlCommand, or even better, a strongly-typed ORM layer like Entity Framework. EF maps SQL types to .Net types automatically, so you would have automatic data type validation if you tried to assign an incompatible value to one of your entity’s properties.Code to parse SQL data types: