Domanda

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.

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top