用于检查依赖关系的SQL查询在SQL server management studio中运行并给出结果时抛出无效。有人能帮我找出里面的错误吗?
我需要有SUM来显示最终结果
public void GetAllTicket()
{
List<DashboardModel> resultlist = new List<DashboardModel>();
using (SqlConnection connection = new SqlConnection(_connString))
{
string query = "SELECT SUM(CASE WHEN [AssignedStaffID] = 8 and [IsAssignedStaffOverridden] = 0 THEN 1 ELSE 0 END) myticket,SUM(CASE WHEN [AgentGroupID] = 1 THEN 1 ELSE 0 END) agentgroup,SUM(CASE WHEN [AssignedStaffID] = 0 AND [AgentGroupID] = 1 THEN 1 ELSE 0 END) newticket,SUM(CASE WHEN [AssignedStaffID] = 8 AND [TicketStatusID] = 2 THEN 1 ELSE 0 END) resolvedticket FROM [dbo].[Ticket]";
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
connection.Open();
DataTable dt = new DataTable();
SqlDataReader reader = command.ExecuteReader();
dt.Load(reader);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
resultlist.Add(new DashboardModel
{
MyTicketCount = int.Parse(dt.Rows[i]["myticket"].ToString()),
AgentGroupTicketCount = int.Parse(dt.Rows[i]["agentgroup"].ToString()),
NewTicketCount = int.Parse(dt.Rows[i]["newticket"].ToString()),
ResolvedTicketCount = int.Parse(dt.Rows[i]["resolvedticket"].ToString())
});
}
}
}
}
NotifyAllClients(resultlist);
}
我在下得到e.info=无效
public void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Info == SqlNotificationInfo.Invalid)
{
Console.WriteLine("The above notification query is not valid.");
}
if (e.Type == SqlNotificationType.Change)
{
GetAllTicket();
}
}
这不是SqlDependency的有效查询,因为您使用了聚合(SUM),但没有group-by子句。关于SqlDependency的microsoft文档如下:https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldependency%28v=vs.110%29.aspx
上面写着
只有满足特定要求列表的SELECT语句才支持查询通知。
有一个链接到一个非常有用的页面,详细列出了所有这些要求,可以在这里找到:https://msdn.microsoft.com/library/ms181122.aspx
有一节关于"支持的SELECT语句",其中有一个小宝石:
SELECT语句中的投影列不能包含聚合表达式,除非该语句使用GROUP BY表达式。
您的查询可能还违反了其他规则,这些规则在代码中并不明显(例如,dbo.tickets是视图吗?)。