Recover Select from Any Trigger

Asked

Viewed 139 times

1

How can I get one back select of a trigger?

Example:

CREATE TABLE PESSOA2
(
    ID INTEGER IDENTITY NOT NULL,
    NOME VARCHAR(250)
)
 CREATE TRIGGER SELECIONAR_NOME2 ON DBO.PESSOA2
AFTER UPDATE AS 

BEGIN 
    SELECT * FROM PESSOA2

END


 INSERT INTO PESSOA2 (NOME) VALUES ('fulano1')
 INSERT INTO PESSOA2 (NOME) VALUES ('fulano2')
 INSERT INTO PESSOA2 (NOME) VALUES ('fulano3')
 INSERT INTO PESSOA2 (NOME) VALUES ('fulano4')
 INSERT INTO PESSOA2 (NOME) VALUES ('fulano5')

UPDATE PESSOA2 SET NOME = 'fulano0' WHERE NOME = 'fulano1'

Result after giving UPDATE: inserir a descrição da imagem aqui
In this example, when I give one update he gives a select on the table pessoa, what I want to know is how I can recover the select via application c#?

Using try{}catch{} I can get an error return, but how to recover select table?

EX to get return:

try
{
    identity = dbCommand.ExecuteXmlReader().toInt32(); //Não conseguiu exercutar? Gera uma Excepition gera um log para análise 
}                                                   // e procura por outra Exception.
catch (Exception e)
{
    if(e.Message == "Comando inválido enviado a ExecuteXmlReader. O comando deve retornar um resultado Xml.")
    {
        return;
    }
    MessageBox.Show(e.Message, "Exceção banco de dados");

}

  • 1

    recover the select? what you mean by that?

  • Hudsonph type, when I update the personal table2 Trigger is triggered, and then make a table select, as I can recover this select via application c#?

  • but what is the need for it? wouldn’t it be better to implement in your service the select returning the new values? pq Trigger + c# 'e to Realtime app

  • I want to update a DataGridView, I have fields with multiple users and Status(online or offline) DataGridView Currently I did with Timer, but it gets bad, updating every time... : D Know a better way? Help me Please... : D

  • 2

    use that nuget https://github.com/christiandelbianco/monitor-table-change-with-sqltabledependency

  • I’ll check... a moment

  • Do I still not understand? First of all Trigger means trigger, male noun, meaning the Rigger is just a trigger fired after a DML event. Second triggers are not used in this way they are mechanisms of propagation of changes, for fields, other tables or other databases, activated after and only the change to which they were associated. Third the only way to recover the cursor for that select create a cursor for that select with DECLARE CURSOR and then open it with OPEN and scroll through that cursor with FETCH. Continues...

  • The problem of this operation is not the difficulty and time it takes to implement it but the impact it causes on the memory and performance of the database server because for each cursor of a SELECT * a MIRROR of the table in question within the server for each active cursor. That said, I ask. It wouldn’t be easier after your UPDATE command makes a SELECT within C#?

  • I took a look at Solution that you sent Hudsonph and I couldn’t understand her, she’s very confused and complex.

  • Hello Augusto, thanks for the answer, so the application I am creating will run several times, imagine the scenario: 10 machine running it, I need to know which of these machines are logged in the application. I did that when logging in an update in the person table and changing your STS to = online. When a person logs in I need to update a Preview menu that will run on another machine, as I will update it?

  • I did with Timer, every 15 seconds make select in the table and update the DataGridView. Only with this it takes time to update and will be updating even if general is Offline. I thought to do with Trigger, when some client update the table and change their STS, then I identify this change and give sselect in the table, ensuring that only when someone gets online or offline again I update the DataGridView

  • 1

    I’ll repeat @Hudsonph’s reply, use the component Sqltabledependency. Just install the package via Nugget and use in your application.

  • Another if you just know who is online and offline is not easier to use the sp-who

  • So, it would be interesting, would know status when connecting with the server, but I’m not a developer, I’m just doing a small project, I thought it would be easier to solve my problem

  • I couldn’t install Nugget.exe it seems that you have to configure an environment variable to be able to run it and dps install it, I can’t install the package through Visual Studio?

  • put an answer and functional example, just need to change model and Connection to test

  • ??? Nugget.exe??? Menu Tools->Nuggets Package Manager->Manage Nugget Package for Solution...

  • It has instator, but the look has this hand on the wheel kkkk I will install here

  • 1

    I think to install you need another version of . Net use 4 for the application

Show 14 more comments

1 answer

2


You can use Sqltabledependency:

using System;
using TableDependency.SqlClient;
using TableDependency.SqlClient.Base.EventArgs;

namespace RealTimeUpdate
{
    public class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Surname { get; set; }
    }


    class Program
    {
        private static string connection = "data source=.; initial catalog=MyDB; integrated security=True";

        static void Main(string[] args)
        {
            SqlTableDependency<Customer> dep;
            using (dep = new SqlTableDependency<Customer>(connection, "Customers"));
            {                
                dep.OnChanged += Changed;
                dep.Start();

                Console.WriteLine("Press a key to exit");
                Console.ReadKey();

                dep.Stop();
            }
        }

        public static void Changed(object sender, RecordChangedEventArgs<Customer> e)
        {
            var changedEntity = e.Entity;

            Console.WriteLine("DML operation: " + e.ChangeType);
            Console.WriteLine("ID: " + changedEntity.Id);
            Console.WriteLine("Name: " + changedEntity.Name);
            Console.WriteLine("Surame: " + changedEntity.Surname);
        }

    }
}

this row refers to the name of your table new SqlTableDependency<Customer>(connection, "Customers") that will be monitored, if you do not have a model with the same name you can use Mapper new SqlTableDependency<Customer>(_con, "Customers", mapper: mapper));.

that line dep.OnChanged += Changed; plus void Changed(object sender, RecordChangedEventArgs<Customer> e) refers to the watch in the chosen table, every time you have a update, insert or delete you will be notified.

Link to the github https://github.com/christiandelbianco/monitor-table-change-with-sqltabledependency


A second option would be Servicebrokerlistener

Enable Broken in db: ALTER DATABASE nomedodb SET ENABLE_BROKER

use the following code in c#:

var listener = new SqlDependencyEx(connectionString, "nomedobancodedados", "nomedatabela");
listener.TableChanged += (o, e) => Console.WriteLine("Faz alguma coisa");
listener.Start();
//listener.Stop();
//desativar o listener

update only:

var listener = new SqlDependencyEx(connectionString, "nomedobancodedados",
             "nomedatabela", listenerType: SqlDependencyEx.NotificationTypes.Update);

Link to the Github: https://github.com/dyatchenko/ServiceBrokerListener

  • Yes I understood, but then it would only be to monitor what was done, use it just to generate log and such, to save the changes, I used Rigger to save the logs. But for what I want I don’t know if it’s useful. I think it’s pretty simple, usually what you use to update a field that gets changed?

  • 1

    for this type of application that needs a real-time response, do not use c# but Node.js combined with the angular interface.

  • @Gustavopedro put a second option in c#

  • Yes, I will test, when the table is changed I run something? I can specify the name of the table column?

  • not but you can validate after you receive the change

  • Yes, I’ll try that and put the result here, thank you :D

  • How do I specify the Table I need? using (dep = new SqlTableDependency<Customer>(connection, "Customers")); You said this is my table, but where do I put the name? ?

  • in place of Customer you put the name of your model (if it is equal to the table name)

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.