Money
和 Decimal
SQL 类型在 .NET 中都被解释为 Decimal
。有什么方法可以区分吗?我正在尝试正确设置 Excel 电子表格的格式,但不知道哪些字段应设置为货币格式,哪些字段应为小数。例如:
+----------------+------------------+--------------+-----------------+
| Name (VarChar) | Weight (Decimal) | Cost (Money) | Inventory (Int) |
+----------------+------------------+--------------+-----------------+
| Widget | 3.75 | 9.99 | 25 |
+----------------+------------------+--------------+-----------------+
上述标题包括用于此问题的数据类型,并且 query
是从该表中进行选择的存储过程:
var result = conn.Query<dynamic>(query, parameters, commandType: CommandType.StoredProcedure).ToList();
foreach (var pair in (IDictionary<string, object>)result[0]) {
Console.WriteLine($"{pair.Key}: {pair.Value.GetType().Name}");
}
将导致:
Name: String
Weight: Decimal
Cost: Decimal
Inventory: Int32
我找到了这篇文章:Money datatype and decimal type of SQL in .net但不幸的是,我没有标准化的列名称,因为这意味着将任何结果集转换为 Excel 电子表格。
我还考虑过更改存储过程以在需要时预先添加美元符号,但这会需要更多工作,并且很可能会破坏其他功能。
是否有不同的方法来确定结果的 SQL 类型?
最佳答案
这是我的解决方案...
我在 VS2019 中创建了一个 localdb(v11.0) ([TestDb].[dbo].[Table])。它有 3 列:
- Id(整数)
- 数字(十进制(18))
- 美元(金钱)
这是我的代码,用于获取架构,然后获取ColumnName及其ProviderSpecificDataType:
[TestMethod]
public void GetProviderSpecificDataType()
{
using (SqlConnection connection = new SqlConnection("Server=(localdb)\\v11.0;Integrated Security=true;"))
{
connection.Open();
SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "select * from [TestDb].[dbo].[Table]";
SqlDataReader reader = cmd.ExecuteReader();
DataTable table = reader.GetSchemaTable();
var columnTypes = GetColumnTypes(table);
Assert.AreEqual("SqlInt32", columnTypes["Id"]);
Assert.AreEqual("SqlDecimal", columnTypes["Number"]);
Assert.AreEqual("SqlMoney", columnTypes["Dollars"]);
}
}
private Dictionary<string, string> GetColumnTypes(DataTable table)
{
Dictionary<string, string> data = new Dictionary<string, string>();
foreach (DataRow row in table.Rows)
{
string columnName = row["ColumnName"].ToString();
string dataType = ((Type)row["ProviderSpecificDataType"]).Name;
data[columnName] = dataType;
}
return data;
}
我的测试通过了......希望这至少能帮助你。
关于c# - 有没有办法区分 .NET 中的 SQL Money 和 Decimal 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50729774/