Make C# Dependency only trigger when new rows have been inserted into MS SQL with specific column valueMake new row dirty programmatically and insert a new row after it in DataGridViewdataset update fails when inserting new rowSQL, T-SQL. TRIGGER or PROCEDURE to duplicate the last row inserted by changing only some valuesSQL Server trigger for a specific column valueC# using SQL dependency to receive notification when query returns no rowsT-SQL Trigger only when column value changesSQL - Trigger that inserts data in to a table only if specific column have been updatedRollback within trigger for one row when multiple rows are in insertedINSERT existing values into new columnSQL Server trigger delete existing row and INSERTED itself

Was Apollo 13 radio blackout on reentry longer than expected?

What is the word for "event executor"?

Alphanumeric Line and Curve Counting

Which GPUs to get for Mathematical Optimization (if any...)?

Does the Intel 8085 CPU use real memory addresses?

What were the problems on the Apollo 11 lunar module?

A Table Representing the altar

Is there a typesafe way to get a Database.QueryLocator?

Operation Unz̖̬̜̺̬a͇͖̯͔͉l̟̭g͕̝̼͇͓̪͍o̬̝͍̹̻

Will this tire fail its MOT?

At which point can a system be compromised when downloading archived data from an untrusted source?

Random piece of plastic

Was Jacobi the first to notice the ambiguity in the partial derivatives notation? And did anyone object to his fix?

Does this sentence I constructed with my junior high school latin work? I write online advertising and want to come off as snobby as possible

Where are the rest of the Dwarves of Nidavellir?

What happens if a company buys back all of its shares?

Is this Android phone Android 9.0 or Android 6.0?

Why do space operations use "nominal" to mean "working correctly"?

Migrating Configuration - 3750G to 3750X

Why does Eliyahu appear at a brit milah?

What would be the safest way to drop thousands of small, hard objects from a typical, high wing, GA airplane?

how slow a car engine can run

Can a Resident Assistant be told to ignore a lawful order?'

Where do the electrons come from to make the carbon stable during bombardment of alpha particles on beryllium



Make C# Dependency only trigger when new rows have been inserted into MS SQL with specific column value


Make new row dirty programmatically and insert a new row after it in DataGridViewdataset update fails when inserting new rowSQL, T-SQL. TRIGGER or PROCEDURE to duplicate the last row inserted by changing only some valuesSQL Server trigger for a specific column valueC# using SQL dependency to receive notification when query returns no rowsT-SQL Trigger only when column value changesSQL - Trigger that inserts data in to a table only if specific column have been updatedRollback within trigger for one row when multiple rows are in insertedINSERT existing values into new columnSQL Server trigger delete existing row and INSERTED itself






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








6















I want to receive a "change" event when new rows have been inserted into MS SQL with specific column value.



Below is the code I currently use, which works fairly well, except that it triggers an event when any row value in [Status] column changes to/ OR from "NEW".



public void InitialiseDependencyWORK(Action onDependencyMethod)


this.onDependencyMethod = onDependencyMethod;

string sqlCommandText = "SELECT [Symbol] FROM [JJ].[Orders] WHERE [Status] = 'NEW'";

using (SqlCommand command = new SqlCommand(sqlCommandText, conn))


Dependency = new SqlDependency(command);

Dependency.OnChange += new OnChangeEventHandler(OnDependencyChange);

using (SqlDataReader reader = command.ExecuteReader())

// Process the DataReader.





void OnDependencyChange(object sender,
SqlNotificationEventArgs e)

// Handles NEW rows



I am only interested when a new row is inserted with [Status] = "NEW", but this event also triggers when there is no new insert BUT [Status] has changed from "NEW" to anything else.



How can I only get a trigger event when there has been a new insert?



I would like to receive a trigger event when news rows have been inserted like row 2 below:



OrderID, Status 
1,Done
2,NEW


I DON'T want it to trigger because row 2 has just had its Status updated - there is actually no new row to process:



OrderID, Status
1,Done
2,Done


How can I achieve this?










share|improve this question






















  • Why delete your old Question and duplicate it? This doesn't add anything to the previous question you had.

    – Larnu
    Mar 26 at 9:15











  • Question restructured to give better explanation of my issue

    – ManInMoon
    Mar 26 at 11:38











  • You could check specifically for inserts in you handler with if(e.Info == "Insert"), ignoring others and resubscribe.

    – Dan Guzman
    Apr 1 at 22:55











  • @DanGuzman What would e.Info return if there where a host of updates and changes?

    – ManInMoon
    Apr 5 at 7:45

















6















I want to receive a "change" event when new rows have been inserted into MS SQL with specific column value.



Below is the code I currently use, which works fairly well, except that it triggers an event when any row value in [Status] column changes to/ OR from "NEW".



public void InitialiseDependencyWORK(Action onDependencyMethod)


this.onDependencyMethod = onDependencyMethod;

string sqlCommandText = "SELECT [Symbol] FROM [JJ].[Orders] WHERE [Status] = 'NEW'";

using (SqlCommand command = new SqlCommand(sqlCommandText, conn))


Dependency = new SqlDependency(command);

Dependency.OnChange += new OnChangeEventHandler(OnDependencyChange);

using (SqlDataReader reader = command.ExecuteReader())

// Process the DataReader.





void OnDependencyChange(object sender,
SqlNotificationEventArgs e)

// Handles NEW rows



I am only interested when a new row is inserted with [Status] = "NEW", but this event also triggers when there is no new insert BUT [Status] has changed from "NEW" to anything else.



How can I only get a trigger event when there has been a new insert?



I would like to receive a trigger event when news rows have been inserted like row 2 below:



OrderID, Status 
1,Done
2,NEW


I DON'T want it to trigger because row 2 has just had its Status updated - there is actually no new row to process:



OrderID, Status
1,Done
2,Done


How can I achieve this?










share|improve this question






















  • Why delete your old Question and duplicate it? This doesn't add anything to the previous question you had.

    – Larnu
    Mar 26 at 9:15











  • Question restructured to give better explanation of my issue

    – ManInMoon
    Mar 26 at 11:38











  • You could check specifically for inserts in you handler with if(e.Info == "Insert"), ignoring others and resubscribe.

    – Dan Guzman
    Apr 1 at 22:55











  • @DanGuzman What would e.Info return if there where a host of updates and changes?

    – ManInMoon
    Apr 5 at 7:45













6












6








6








I want to receive a "change" event when new rows have been inserted into MS SQL with specific column value.



Below is the code I currently use, which works fairly well, except that it triggers an event when any row value in [Status] column changes to/ OR from "NEW".



public void InitialiseDependencyWORK(Action onDependencyMethod)


this.onDependencyMethod = onDependencyMethod;

string sqlCommandText = "SELECT [Symbol] FROM [JJ].[Orders] WHERE [Status] = 'NEW'";

using (SqlCommand command = new SqlCommand(sqlCommandText, conn))


Dependency = new SqlDependency(command);

Dependency.OnChange += new OnChangeEventHandler(OnDependencyChange);

using (SqlDataReader reader = command.ExecuteReader())

// Process the DataReader.





void OnDependencyChange(object sender,
SqlNotificationEventArgs e)

// Handles NEW rows



I am only interested when a new row is inserted with [Status] = "NEW", but this event also triggers when there is no new insert BUT [Status] has changed from "NEW" to anything else.



How can I only get a trigger event when there has been a new insert?



I would like to receive a trigger event when news rows have been inserted like row 2 below:



OrderID, Status 
1,Done
2,NEW


I DON'T want it to trigger because row 2 has just had its Status updated - there is actually no new row to process:



OrderID, Status
1,Done
2,Done


How can I achieve this?










share|improve this question














I want to receive a "change" event when new rows have been inserted into MS SQL with specific column value.



Below is the code I currently use, which works fairly well, except that it triggers an event when any row value in [Status] column changes to/ OR from "NEW".



public void InitialiseDependencyWORK(Action onDependencyMethod)


this.onDependencyMethod = onDependencyMethod;

string sqlCommandText = "SELECT [Symbol] FROM [JJ].[Orders] WHERE [Status] = 'NEW'";

using (SqlCommand command = new SqlCommand(sqlCommandText, conn))


Dependency = new SqlDependency(command);

Dependency.OnChange += new OnChangeEventHandler(OnDependencyChange);

using (SqlDataReader reader = command.ExecuteReader())

// Process the DataReader.





void OnDependencyChange(object sender,
SqlNotificationEventArgs e)

// Handles NEW rows



I am only interested when a new row is inserted with [Status] = "NEW", but this event also triggers when there is no new insert BUT [Status] has changed from "NEW" to anything else.



How can I only get a trigger event when there has been a new insert?



I would like to receive a trigger event when news rows have been inserted like row 2 below:



OrderID, Status 
1,Done
2,NEW


I DON'T want it to trigger because row 2 has just had its Status updated - there is actually no new row to process:



OrderID, Status
1,Done
2,Done


How can I achieve this?







c# sql-server dependencies






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 26 at 9:13









ManInMoonManInMoon

2,61512 gold badges41 silver badges90 bronze badges




2,61512 gold badges41 silver badges90 bronze badges












  • Why delete your old Question and duplicate it? This doesn't add anything to the previous question you had.

    – Larnu
    Mar 26 at 9:15











  • Question restructured to give better explanation of my issue

    – ManInMoon
    Mar 26 at 11:38











  • You could check specifically for inserts in you handler with if(e.Info == "Insert"), ignoring others and resubscribe.

    – Dan Guzman
    Apr 1 at 22:55











  • @DanGuzman What would e.Info return if there where a host of updates and changes?

    – ManInMoon
    Apr 5 at 7:45

















  • Why delete your old Question and duplicate it? This doesn't add anything to the previous question you had.

    – Larnu
    Mar 26 at 9:15











  • Question restructured to give better explanation of my issue

    – ManInMoon
    Mar 26 at 11:38











  • You could check specifically for inserts in you handler with if(e.Info == "Insert"), ignoring others and resubscribe.

    – Dan Guzman
    Apr 1 at 22:55











  • @DanGuzman What would e.Info return if there where a host of updates and changes?

    – ManInMoon
    Apr 5 at 7:45
















Why delete your old Question and duplicate it? This doesn't add anything to the previous question you had.

– Larnu
Mar 26 at 9:15





Why delete your old Question and duplicate it? This doesn't add anything to the previous question you had.

– Larnu
Mar 26 at 9:15













Question restructured to give better explanation of my issue

– ManInMoon
Mar 26 at 11:38





Question restructured to give better explanation of my issue

– ManInMoon
Mar 26 at 11:38













You could check specifically for inserts in you handler with if(e.Info == "Insert"), ignoring others and resubscribe.

– Dan Guzman
Apr 1 at 22:55





You could check specifically for inserts in you handler with if(e.Info == "Insert"), ignoring others and resubscribe.

– Dan Guzman
Apr 1 at 22:55













@DanGuzman What would e.Info return if there where a host of updates and changes?

– ManInMoon
Apr 5 at 7:45





@DanGuzman What would e.Info return if there where a host of updates and changes?

– ManInMoon
Apr 5 at 7:45












3 Answers
3






active

oldest

votes


















2














May I ask why you are reinventing SQL triggers in c# for context?
https://docs.microsoft.com/en-us/sql/t-sql/statements/create-trigger-transact-sql?view=sql-server-2017



The simplest solution is to capture this at the table itself and not via a query which will yield false positives.



Alternatively if you are running all of your code via a repository layer then you should be able to differentiate an INSERT from an UPDATE and pick it off there too.






share|improve this answer























  • Not sure what you mean by reineventing. I am USING c# functionality to receive an event trigger within my c# application, as it is the application that wants to do something on an insert event. Can I use your suggestion to achieve this?

    – ManInMoon
    Mar 28 at 1:59











  • Sorry for the delayed response ManInMoon. If the only possible path for edits is through your application and you have a business logic layer or repository pattern in which all edits run through that single point you could preemptively determine edits prior to them taking place as noted previously. This is sketchy to me as you are locking into the thought that you will only ever allow changes through that single point.This is of course ideal, but you must ensure that all edits to that data only occur via that single point. At the table level you are assured to capture it.

    – David
    Apr 4 at 11:48


















2





+25









The general use case of using SqlDependency is for detecting changes to data that doesn't change very often that you would like to cache, but also need to know if it does change so you can refresh the cache without polling the database. Your case is slightly different in that you don't really want to know when the results of that query changes... you want to know when a certain query contains results to process. The reason you're getting the notification when the status code changes to AND from "NEW" is because both of those types of changes will alter the query results. It is adding and subtracting entire rows based on both kinds of change.



If you are only using the status codes "NEW" and "DONE" and they are guaranteed to always initiate as "NEW" and progress only forward to "DONE" (and never back), then a workaround might be to use this query:



SELECT [OrderID] FROM [JJ].[Orders] WHERE [Status] <= 'NEW'


This way a new item added in status "NEW" will change the query results... but when it moves to "DONE" it will still be an OrderID returned in the query and should not trigger a change event. If you have more status values you progress though... you might consider using an integer in your status column to indicate the progression. For example 0 for new, 1 for in progress, 2 done... etc.



It sounds like you are trying to create some kind of queue of work to be done and there are other ways to do that sort of thing also. There is SQL Server Change Tracking and Data Change Tracking, Triggers, Service Broker Queues, and lots of other queuing technologies. You might check into them as well as options for your architecture.






share|improve this answer






























    0














    I think SqlDependency event fire whenever there is any Insert/Update/Delete in Table.



    There is no way of stopping it.



    you can catch the appropriate notification type in event and do you work.



    void OnDependencyChange(object sender,
    SqlNotificationEventArgs e)

    if (e.Info == SqlNotificationInfo.Insert)



    Other Way of doing it which I hvn't tried,



    Create another table OrdersCopy which is replica of [JJ].[Orders]



    Create Insert Trigger in Order table.



    Whenever there is insert in Order table,trigger will fire.
    Insert the new record in OrdersCopy



    Here do the following change, change the table name to OrderCopy



    string sqlCommandText = "SELECT [Symbol] FROM [JJ].[OrdersCopy] WHERE [Status] = 'NEW'";


    For experiment shake,you can try this once.



    OnDependencyChange event will only fire in case of Insert.






    share|improve this answer

























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55353413%2fmake-c-sharp-dependency-only-trigger-when-new-rows-have-been-inserted-into-ms-sq%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      May I ask why you are reinventing SQL triggers in c# for context?
      https://docs.microsoft.com/en-us/sql/t-sql/statements/create-trigger-transact-sql?view=sql-server-2017



      The simplest solution is to capture this at the table itself and not via a query which will yield false positives.



      Alternatively if you are running all of your code via a repository layer then you should be able to differentiate an INSERT from an UPDATE and pick it off there too.






      share|improve this answer























      • Not sure what you mean by reineventing. I am USING c# functionality to receive an event trigger within my c# application, as it is the application that wants to do something on an insert event. Can I use your suggestion to achieve this?

        – ManInMoon
        Mar 28 at 1:59











      • Sorry for the delayed response ManInMoon. If the only possible path for edits is through your application and you have a business logic layer or repository pattern in which all edits run through that single point you could preemptively determine edits prior to them taking place as noted previously. This is sketchy to me as you are locking into the thought that you will only ever allow changes through that single point.This is of course ideal, but you must ensure that all edits to that data only occur via that single point. At the table level you are assured to capture it.

        – David
        Apr 4 at 11:48















      2














      May I ask why you are reinventing SQL triggers in c# for context?
      https://docs.microsoft.com/en-us/sql/t-sql/statements/create-trigger-transact-sql?view=sql-server-2017



      The simplest solution is to capture this at the table itself and not via a query which will yield false positives.



      Alternatively if you are running all of your code via a repository layer then you should be able to differentiate an INSERT from an UPDATE and pick it off there too.






      share|improve this answer























      • Not sure what you mean by reineventing. I am USING c# functionality to receive an event trigger within my c# application, as it is the application that wants to do something on an insert event. Can I use your suggestion to achieve this?

        – ManInMoon
        Mar 28 at 1:59











      • Sorry for the delayed response ManInMoon. If the only possible path for edits is through your application and you have a business logic layer or repository pattern in which all edits run through that single point you could preemptively determine edits prior to them taking place as noted previously. This is sketchy to me as you are locking into the thought that you will only ever allow changes through that single point.This is of course ideal, but you must ensure that all edits to that data only occur via that single point. At the table level you are assured to capture it.

        – David
        Apr 4 at 11:48













      2












      2








      2







      May I ask why you are reinventing SQL triggers in c# for context?
      https://docs.microsoft.com/en-us/sql/t-sql/statements/create-trigger-transact-sql?view=sql-server-2017



      The simplest solution is to capture this at the table itself and not via a query which will yield false positives.



      Alternatively if you are running all of your code via a repository layer then you should be able to differentiate an INSERT from an UPDATE and pick it off there too.






      share|improve this answer













      May I ask why you are reinventing SQL triggers in c# for context?
      https://docs.microsoft.com/en-us/sql/t-sql/statements/create-trigger-transact-sql?view=sql-server-2017



      The simplest solution is to capture this at the table itself and not via a query which will yield false positives.



      Alternatively if you are running all of your code via a repository layer then you should be able to differentiate an INSERT from an UPDATE and pick it off there too.







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Mar 26 at 12:14









      DavidDavid

      513 bronze badges




      513 bronze badges












      • Not sure what you mean by reineventing. I am USING c# functionality to receive an event trigger within my c# application, as it is the application that wants to do something on an insert event. Can I use your suggestion to achieve this?

        – ManInMoon
        Mar 28 at 1:59











      • Sorry for the delayed response ManInMoon. If the only possible path for edits is through your application and you have a business logic layer or repository pattern in which all edits run through that single point you could preemptively determine edits prior to them taking place as noted previously. This is sketchy to me as you are locking into the thought that you will only ever allow changes through that single point.This is of course ideal, but you must ensure that all edits to that data only occur via that single point. At the table level you are assured to capture it.

        – David
        Apr 4 at 11:48

















      • Not sure what you mean by reineventing. I am USING c# functionality to receive an event trigger within my c# application, as it is the application that wants to do something on an insert event. Can I use your suggestion to achieve this?

        – ManInMoon
        Mar 28 at 1:59











      • Sorry for the delayed response ManInMoon. If the only possible path for edits is through your application and you have a business logic layer or repository pattern in which all edits run through that single point you could preemptively determine edits prior to them taking place as noted previously. This is sketchy to me as you are locking into the thought that you will only ever allow changes through that single point.This is of course ideal, but you must ensure that all edits to that data only occur via that single point. At the table level you are assured to capture it.

        – David
        Apr 4 at 11:48
















      Not sure what you mean by reineventing. I am USING c# functionality to receive an event trigger within my c# application, as it is the application that wants to do something on an insert event. Can I use your suggestion to achieve this?

      – ManInMoon
      Mar 28 at 1:59





      Not sure what you mean by reineventing. I am USING c# functionality to receive an event trigger within my c# application, as it is the application that wants to do something on an insert event. Can I use your suggestion to achieve this?

      – ManInMoon
      Mar 28 at 1:59













      Sorry for the delayed response ManInMoon. If the only possible path for edits is through your application and you have a business logic layer or repository pattern in which all edits run through that single point you could preemptively determine edits prior to them taking place as noted previously. This is sketchy to me as you are locking into the thought that you will only ever allow changes through that single point.This is of course ideal, but you must ensure that all edits to that data only occur via that single point. At the table level you are assured to capture it.

      – David
      Apr 4 at 11:48





      Sorry for the delayed response ManInMoon. If the only possible path for edits is through your application and you have a business logic layer or repository pattern in which all edits run through that single point you could preemptively determine edits prior to them taking place as noted previously. This is sketchy to me as you are locking into the thought that you will only ever allow changes through that single point.This is of course ideal, but you must ensure that all edits to that data only occur via that single point. At the table level you are assured to capture it.

      – David
      Apr 4 at 11:48













      2





      +25









      The general use case of using SqlDependency is for detecting changes to data that doesn't change very often that you would like to cache, but also need to know if it does change so you can refresh the cache without polling the database. Your case is slightly different in that you don't really want to know when the results of that query changes... you want to know when a certain query contains results to process. The reason you're getting the notification when the status code changes to AND from "NEW" is because both of those types of changes will alter the query results. It is adding and subtracting entire rows based on both kinds of change.



      If you are only using the status codes "NEW" and "DONE" and they are guaranteed to always initiate as "NEW" and progress only forward to "DONE" (and never back), then a workaround might be to use this query:



      SELECT [OrderID] FROM [JJ].[Orders] WHERE [Status] <= 'NEW'


      This way a new item added in status "NEW" will change the query results... but when it moves to "DONE" it will still be an OrderID returned in the query and should not trigger a change event. If you have more status values you progress though... you might consider using an integer in your status column to indicate the progression. For example 0 for new, 1 for in progress, 2 done... etc.



      It sounds like you are trying to create some kind of queue of work to be done and there are other ways to do that sort of thing also. There is SQL Server Change Tracking and Data Change Tracking, Triggers, Service Broker Queues, and lots of other queuing technologies. You might check into them as well as options for your architecture.






      share|improve this answer



























        2





        +25









        The general use case of using SqlDependency is for detecting changes to data that doesn't change very often that you would like to cache, but also need to know if it does change so you can refresh the cache without polling the database. Your case is slightly different in that you don't really want to know when the results of that query changes... you want to know when a certain query contains results to process. The reason you're getting the notification when the status code changes to AND from "NEW" is because both of those types of changes will alter the query results. It is adding and subtracting entire rows based on both kinds of change.



        If you are only using the status codes "NEW" and "DONE" and they are guaranteed to always initiate as "NEW" and progress only forward to "DONE" (and never back), then a workaround might be to use this query:



        SELECT [OrderID] FROM [JJ].[Orders] WHERE [Status] <= 'NEW'


        This way a new item added in status "NEW" will change the query results... but when it moves to "DONE" it will still be an OrderID returned in the query and should not trigger a change event. If you have more status values you progress though... you might consider using an integer in your status column to indicate the progression. For example 0 for new, 1 for in progress, 2 done... etc.



        It sounds like you are trying to create some kind of queue of work to be done and there are other ways to do that sort of thing also. There is SQL Server Change Tracking and Data Change Tracking, Triggers, Service Broker Queues, and lots of other queuing technologies. You might check into them as well as options for your architecture.






        share|improve this answer

























          2





          +25







          2





          +25



          2




          +25





          The general use case of using SqlDependency is for detecting changes to data that doesn't change very often that you would like to cache, but also need to know if it does change so you can refresh the cache without polling the database. Your case is slightly different in that you don't really want to know when the results of that query changes... you want to know when a certain query contains results to process. The reason you're getting the notification when the status code changes to AND from "NEW" is because both of those types of changes will alter the query results. It is adding and subtracting entire rows based on both kinds of change.



          If you are only using the status codes "NEW" and "DONE" and they are guaranteed to always initiate as "NEW" and progress only forward to "DONE" (and never back), then a workaround might be to use this query:



          SELECT [OrderID] FROM [JJ].[Orders] WHERE [Status] <= 'NEW'


          This way a new item added in status "NEW" will change the query results... but when it moves to "DONE" it will still be an OrderID returned in the query and should not trigger a change event. If you have more status values you progress though... you might consider using an integer in your status column to indicate the progression. For example 0 for new, 1 for in progress, 2 done... etc.



          It sounds like you are trying to create some kind of queue of work to be done and there are other ways to do that sort of thing also. There is SQL Server Change Tracking and Data Change Tracking, Triggers, Service Broker Queues, and lots of other queuing technologies. You might check into them as well as options for your architecture.






          share|improve this answer













          The general use case of using SqlDependency is for detecting changes to data that doesn't change very often that you would like to cache, but also need to know if it does change so you can refresh the cache without polling the database. Your case is slightly different in that you don't really want to know when the results of that query changes... you want to know when a certain query contains results to process. The reason you're getting the notification when the status code changes to AND from "NEW" is because both of those types of changes will alter the query results. It is adding and subtracting entire rows based on both kinds of change.



          If you are only using the status codes "NEW" and "DONE" and they are guaranteed to always initiate as "NEW" and progress only forward to "DONE" (and never back), then a workaround might be to use this query:



          SELECT [OrderID] FROM [JJ].[Orders] WHERE [Status] <= 'NEW'


          This way a new item added in status "NEW" will change the query results... but when it moves to "DONE" it will still be an OrderID returned in the query and should not trigger a change event. If you have more status values you progress though... you might consider using an integer in your status column to indicate the progression. For example 0 for new, 1 for in progress, 2 done... etc.



          It sounds like you are trying to create some kind of queue of work to be done and there are other ways to do that sort of thing also. There is SQL Server Change Tracking and Data Change Tracking, Triggers, Service Broker Queues, and lots of other queuing technologies. You might check into them as well as options for your architecture.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Apr 2 at 23:04









          Brian PresslerBrian Pressler

          6,0161 gold badge14 silver badges39 bronze badges




          6,0161 gold badge14 silver badges39 bronze badges





















              0














              I think SqlDependency event fire whenever there is any Insert/Update/Delete in Table.



              There is no way of stopping it.



              you can catch the appropriate notification type in event and do you work.



              void OnDependencyChange(object sender,
              SqlNotificationEventArgs e)

              if (e.Info == SqlNotificationInfo.Insert)



              Other Way of doing it which I hvn't tried,



              Create another table OrdersCopy which is replica of [JJ].[Orders]



              Create Insert Trigger in Order table.



              Whenever there is insert in Order table,trigger will fire.
              Insert the new record in OrdersCopy



              Here do the following change, change the table name to OrderCopy



              string sqlCommandText = "SELECT [Symbol] FROM [JJ].[OrdersCopy] WHERE [Status] = 'NEW'";


              For experiment shake,you can try this once.



              OnDependencyChange event will only fire in case of Insert.






              share|improve this answer



























                0














                I think SqlDependency event fire whenever there is any Insert/Update/Delete in Table.



                There is no way of stopping it.



                you can catch the appropriate notification type in event and do you work.



                void OnDependencyChange(object sender,
                SqlNotificationEventArgs e)

                if (e.Info == SqlNotificationInfo.Insert)



                Other Way of doing it which I hvn't tried,



                Create another table OrdersCopy which is replica of [JJ].[Orders]



                Create Insert Trigger in Order table.



                Whenever there is insert in Order table,trigger will fire.
                Insert the new record in OrdersCopy



                Here do the following change, change the table name to OrderCopy



                string sqlCommandText = "SELECT [Symbol] FROM [JJ].[OrdersCopy] WHERE [Status] = 'NEW'";


                For experiment shake,you can try this once.



                OnDependencyChange event will only fire in case of Insert.






                share|improve this answer

























                  0












                  0








                  0







                  I think SqlDependency event fire whenever there is any Insert/Update/Delete in Table.



                  There is no way of stopping it.



                  you can catch the appropriate notification type in event and do you work.



                  void OnDependencyChange(object sender,
                  SqlNotificationEventArgs e)

                  if (e.Info == SqlNotificationInfo.Insert)



                  Other Way of doing it which I hvn't tried,



                  Create another table OrdersCopy which is replica of [JJ].[Orders]



                  Create Insert Trigger in Order table.



                  Whenever there is insert in Order table,trigger will fire.
                  Insert the new record in OrdersCopy



                  Here do the following change, change the table name to OrderCopy



                  string sqlCommandText = "SELECT [Symbol] FROM [JJ].[OrdersCopy] WHERE [Status] = 'NEW'";


                  For experiment shake,you can try this once.



                  OnDependencyChange event will only fire in case of Insert.






                  share|improve this answer













                  I think SqlDependency event fire whenever there is any Insert/Update/Delete in Table.



                  There is no way of stopping it.



                  you can catch the appropriate notification type in event and do you work.



                  void OnDependencyChange(object sender,
                  SqlNotificationEventArgs e)

                  if (e.Info == SqlNotificationInfo.Insert)



                  Other Way of doing it which I hvn't tried,



                  Create another table OrdersCopy which is replica of [JJ].[Orders]



                  Create Insert Trigger in Order table.



                  Whenever there is insert in Order table,trigger will fire.
                  Insert the new record in OrdersCopy



                  Here do the following change, change the table name to OrderCopy



                  string sqlCommandText = "SELECT [Symbol] FROM [JJ].[OrdersCopy] WHERE [Status] = 'NEW'";


                  For experiment shake,you can try this once.



                  OnDependencyChange event will only fire in case of Insert.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Apr 5 at 10:36









                  KumarHarshKumarHarsh

                  3,7441 gold badge12 silver badges18 bronze badges




                  3,7441 gold badge12 silver badges18 bronze badges



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55353413%2fmake-c-sharp-dependency-only-trigger-when-new-rows-have-been-inserted-into-ms-sq%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                      SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                      은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현