SQLDependency + Service Broker

╄→尐↘猪︶ㄣ 提交于 2019-12-10 17:55:54

问题


I'm using SqlDependency to get notification when data in some table are changed.

    private void subscribeBroker()
    {
        using (var conn = new SqlConnection(connString))
        {
            conn.Open();

            var cmd = new SqlCommand("SELECT text FROM dbo.Test");
            cmd.Connection = conn;

            var dependency = new SqlDependency(cmd);
            dependency.OnChange += dependency_OnChange;
            SqlDependency.Start(connString);

            cmd.ExecuteNonQuery();
        }
    }

    void dependency_OnChange(object sender, SqlNotificationEventArgs e)
    {
        //Do something...
        subscribeBroker();
    }

It is working but I have some questions.

1) I didn't find a way how to get information which row was changed. I need to read all data from entire table to see what is different. Is there a way how to get this information? (primary ID, or something) Maybe to use different approach than SqlDependency?

2) What if "somebody" changing data very fast. It is possible that some changes will not being notified? (I'm concerned about time between notification and time when I subscribe it again.

Thank you.


回答1:


About 1- query notification informs you about the fact, that something is changed. If you want to get what was changed since last time- you could probably use timestamp column.

About 2- query notification informs you about changes and then is dropped. then you again subscribe for notification again. that mean- time between dropping and creation of notifications is that time in which notification about changes is not send.

Query notifications is more for the situations, when your data is not changing frequently. For example- some cashed classification values. So- you subscribe for changes in some table, wait for changes and at the time they happen you get latest version of data. Should consider that query notification also uses server resources, so if you have huge table and want to get changes on some small subset of data, a lot of queries can be affected in terms of performance (something like indexed view).

If you need to take some action based on changed data and each change is important, then i would guess that trigger + service broker could be more effective. Or, depending on your needs, Change Data Capture.



来源:https://stackoverflow.com/questions/13033362/sqldependency-service-broker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!