如何确定要添加到参数的变量的 SQLDBType?

发布于 2024-07-14 11:23:53 字数 388 浏览 9 评论 0原文

如何根据要存储在数据库中的输入变量确定将哪个 SQLDBType 分配给参数? 是否有 GetType 等效项可供测试?

If IsNumeric(ParameterValue) Then
    Parameter.SqlDbType = SqlDbType.Float
ElseIf IsDate(ParameterValue) Then
    Parameter.SqlDbType = SqlDbType.DateTime
ElseIf IsArray(ParameterValue) Then
    Parameter.SqlDbType = SqlDbType.VarBinary
Else
    Parameter.SqlDbType = SqlDbType.VarChar
End If

How do I determine which SQLDBType to assign to a parameter depending on the input variable to store in the DB? Is there a GetType equivelant to test with?

If IsNumeric(ParameterValue) Then
    Parameter.SqlDbType = SqlDbType.Float
ElseIf IsDate(ParameterValue) Then
    Parameter.SqlDbType = SqlDbType.DateTime
ElseIf IsArray(ParameterValue) Then
    Parameter.SqlDbType = SqlDbType.VarBinary
Else
    Parameter.SqlDbType = SqlDbType.VarChar
End If

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

温馨耳语 2024-07-21 11:23:53

有太多的 SqlDbType(跨太多版本),无法按照您想要的方式安全地执行此操作,特别是如果您需要使用更精确的数据类型(例如,十进制而不是浮点型,甚至是 bigint)。

我会考虑使用 SMO 在 .NET 数据类型和 SqlDbTypes 之间创建一个简单的映射系统。 然后,您只需根据存储数据的需要将参数映射到数据库类型。

好处是,如果您现在就开始这项工作,您可以重用该库,或者创建一个接口并为每个版本的 SQL 扩展它。


试试这个(C# 代码):

// Get the DataType from the DataRow in your result set
public void GetDataType(DataRow dr)
{
    DataType dt = new DataType((SqlDataType)Enum.Parse(typeof(SqlDataType), dr["DataTypeName"].ToString(), true))
    {
        MaximumLength = Convert.ToInt32(dr["ColumnSize"]),
        NumericPrecision = Convert.ToInt32(dr["NumericPrecision"])
    };
    // TODO: Map DataType to .NET datatype
}

There are too many SqlDbTypes (across too many versions) to do it the safely the way you want to, especially if you need to use more precise data types (e.g. decimal as opposed to float, or even bigint).

I would consider creating a simple mapping system between .NET data types and SqlDbTypes, using SMO. Then you simply map your parameters to the DB type as you require for storing the data.

The nice thing is that if you go to this effort now, you can reuse the library, or create an interface and extend it for each version of SQL.


Try this (C# code):

// Get the DataType from the DataRow in your result set
public void GetDataType(DataRow dr)
{
    DataType dt = new DataType((SqlDataType)Enum.Parse(typeof(SqlDataType), dr["DataTypeName"].ToString(), true))
    {
        MaximumLength = Convert.ToInt32(dr["ColumnSize"]),
        NumericPrecision = Convert.ToInt32(dr["NumericPrecision"])
    };
    // TODO: Map DataType to .NET datatype
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文