所以我试图用MSSQL查询中的数据填充DataTable,但由于某种原因它完全拒绝工作,而且它让我非常恼火。
当我使用SqlDataReader和Read()迭代结果时,我得到了结果,即使我尝试使用SqlDataAdapter填充DataTable,查询也会出现在SQL事件探查器上,但是并没有返回任何结果数据
我不知道我的代码拥有什么,但也许你可以弄明白:
try
{
// Global variables
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
var textString = "Pasākums {0} sākas pēc {1}!";
var linkString = @"/Event/Index/{0}";
using (SqlConnection conn = new SqlConnection(connectionString))
{
// Set variables
var findIn24HrsEventsCmd = new SqlCommand(@"
SELECT adm.UserID, adm.EventID FROM [dbo].[EventAdmissions] AS adm WHERE EventID IN
(
SELECT EventID FROM [dbo].[Events]
WHERE DATEDIFF(hour, @date, StartTime) BETWEEN 0 AND 24
)
AND
(
SELECT COUNT(URL) FROM [dbo].[Notifications]
WHERE Type = 1 AND UserID = adm.UserID
AND URL LIKE '/Event/Index/'+CAST(adm.EventID AS VARCHAR(36))
) = 0", conn);
findIn24HrsEventsCmd.Parameters.Add(new SqlParameter("date", "2015-05-31 02:17:28.727"));
var test = new SqlCommand(@"SELECT * FROM [dbo].[EventAdmissions]", conn);
var findIn1HrEventsCmd = new SqlCommand(@"
SELECT adm.UserID, adm.EventID FROM [dbo].[EventAdmissions] AS adm WHERE EventID IN
(
SELECT EventID FROM [dbo].[Events]
WHERE DATEDIFF(minute, @date, StartTime) BETWEEN 0 AND 60
)
AND
(
SELECT COUNT(URL) FROM [dbo].[Notifications]
WHERE Type = 1 AND UserID = adm.UserID
AND URL LIKE '/Event/Index/'+CAST(adm.EventID AS VARCHAR(36))
) < 2", conn);
findIn1HrEventsCmd.Parameters.Add(new SqlParameter("date", "2015-05-31 02:17:28.727"));
var t = findIn1HrEventsCmd.CommandTimeout;
// Retrieve data
conn.Open();
log.Debug("Starting with the events that are on in an hour.");
// Do it first for evens within an hour
var oneHrDataAdapter = new SqlDataAdapter(test);
var oneHrDt = new DataTable();
oneHrDataAdapter.Fill(oneHrDt);
findIn1HrEventsCmd.Dispose();
findIn24HrsEventsCmd.Dispose();
oneHrDataAdapter.Dispose();
}
} catch (Exception e)
{
log.Fatal("Fatal error!" + e.Message);
}
请注意我是如何将复杂查询替换为一个非常简单的测试查询,该查询肯定会在Management Studio和DataReader中返回结果,但由于某种原因无法使用DataTable。请注意,它不会超时,服务器位于同一台计算机上,查询最多运行1-2秒。
连接有效,因为正如我在DataReader方法之前提到的那样,并且没有抛出异常。
答案 0 :(得分:2)
该死的,我从不打扰检查DataTable的Rows属性,结果证明它确实有效。
我认为它没有,因为在调试模式下,Visual Studio会产生误导,因为当您将鼠标悬停在数据表变量上时,它只会显示&#34; {}&#34;这通常意味着事情是空的。