在我的 C# 项目中,我正在对 SQL 2014 数据库执行查询以检索Employee
数据,包括PeriodEnd
作为 a 存储在数据库中的 a Decimal
(即,2016 年 11 月 17 日存储为 20161117)。我正在查询的数据库不是我们的产品,所以我无法将类型更改为DateTime
字段。
这是正在执行的 SQL 脚本:
SELECT DISTINCT
e.EMPLOYEE as EmpNo,
ch.PEREND As PeriodEnd,
ch.PRPOSTSTAT
FROM UPEMPL e
INNER JOIN UPCHKH ch
ON e.EMPLOYEE = ch.EMPLOYEE
WHERE
ch.PEREND = @PERIODEND
这是SqlDataAdapter
电话:
ExecuteSqlCommandScript(String sqlScript, List<SqlParams> sqlParams)
{
. . . (setup SqlConnection info)
using (SqlConnection _conn = new SqlConnection(connectionString))
{
using (SqlCommand _cmd = new SqlCommand())
{
_cmd.CommandText = sqlScript;
_cmd.Connection = _conn;
_cmd.Connection.Open();
// add SqlParameters to SQL command
if (sqlParams != null)
{
_cmd.Parameters.AddRange(sqlParams.ToArray());
}
using (SqlDataAdapter _sqlDataAdapter = new SqlDataAdapter(_cmd))
{
try
{
// Save Table info to Results object
DataSet _dataSet = new DataSet();
_sqlDataAdapter.Fill(_dataSet);
SqlResult _result = new SqlResult();
_result.DataSet = _dataSet;
_result.TableCount = _dataSet.Tables.Count;
this.Results.Add(_result);
}
}
}
}
}
使用 SQL Server Profiler 我可以看到传递给 SQL 的查询是:
exec sp_executesql N'
SELECT DISTINCT
e.EMPLOYEE as EmpNo,
ch.PEREND As PeriodEnd,
ch.PRPOSTSTAT
FROM UPEMPL e
INNER JOIN UPCHKH ch
ON e.EMPLOYEE = ch.EMPLOYEE
WHERE
ch.PEREND = @PERIODEND
',N'@PERIODEND nvarchar(8)',@PERIODEND=N'20161101'
如果我直接在 SQL 中运行它,结果如下:
但是,DataTable
创建的结果_sqlDataAdapter
是:
有没有办法强制SqlDataAdapter
使用结果中的数据类型?或者是否有可能 SQL 确实返回了一个DateTime
对象而不是 a Decimal
(该PeriodEnd
列在 SQL 中定义为decimal(9,0)
)?如果是这样,是否有这样做的原因和/或防止它的方法?