SQL Server data type compatibilty
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 开发者_C百科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
, and money
. 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 SqlCommand
using 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 get FormatExceptions
.
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:
try
{
// throws FormatExcpetion
System.Data.SqlTypes.SqlInt16 i = System.Data.SqlTypes.SqlInt16.Parse("test");
}
catch (FormatException)
{
// handle it
}
try
{
// i will be set to 10
System.Data.SqlTypes.SqlInt16 i = System.Data.SqlTypes.SqlInt16.Parse("10");
}
catch (FormatException)
{
// handle it
}
精彩评论