How do I get the SqlDbType of a column in a table using ADO.NET?(如何使用 ADO.NET 获取表中列的 SqlDbType?)
问题描述
我试图在运行时确定 sql server 表列的 SqlDbType 是什么.
I'm trying to determine at runtime what the SqlDbType of a sql server table column is.
是否有一个类可以在 System.Data.SqlClient 中执行此操作,还是我应该自己进行映射?我可以从
is there a class that can do that in System.Data.SqlClient or should I do the mapping myself? I can get a string representation back from
SELECT DATA_TYPE, CHARACTER_MAXIMUM_LENGTH
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_CATALOG = '{0}' AND TABLE_SCHEMA = '{1}'
AND TABLE_NAME = '{2}' AND COLUMN_NAME = '{3}'
我不能使用 SMO,因为我无法控制执行机器,所以我不能保证它会被安装.(抱歉没有说清楚 rp).
I can't use SMO as I have no control over the executing machine so I can't guarantee it will be installed. (Sorry for not making that clear rp).
作为对 Joel 的回答,我正在尝试创建一个可以调用的函数,当传递一个 SqlConnection、一个表名和一个列名时,它将返回一个 SqlDBType.
In answer to Joel, I'm trying to make a function that I can call that will return me a SqlDBType when passed a SqlConnection, a table name, and a column name.
推荐答案
在 SQL Server 中,您可以使用 FMTONLY 选项.它允许您在不获取任何数据的情况下运行查询,只返回列.
In SQL Server you can use the FMTONLY option. It allows you to run a query without getting any data, just returning the columns.
SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "SET FMTONLY ON; select column from table; SET FMTONLY OFF";
SqlDataReader reader = cmd.ExecuteReader();
SqlDbType type = (SqlDbType)(int)reader.GetSchemaTable().Rows[0]["ProviderType"];
这篇关于如何使用 ADO.NET 获取表中列的 SqlDbType?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 ADO.NET 获取表中列的 SqlDbType?
基础教程推荐
- 从 C# 控制相机设备 2022-01-01
- 将数据集转换为列表 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 如果条件可以为空 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
