How to define multiple variables at once within a Trigger in Sqlserver

Asked

Viewed 340 times

0

Hello, I am creating a TRIGGER where I must do a series of treatments after an UPDATE in a table in Sqlserver. In this TRIGGER, I need to define some variables so I can work with them in the rest of the script, like this:

CREATE TABLE foo (
    id INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
    nome NVARCHAR(100) NOT NULL,
    telefone NVARCHAR(30) NOT NULL DEFAULT '',
    email NVARCHAR(100) NOT NULL DEFAULT ''
);

GO

CREATE TRIGGER [TR_foo_onUpdate] ON foo AFTER UPDATE AS
BEGIN

    SET NOCOUNT ON;

    DECLARE @id BIT = (SELECT id FROM inserted),
            @nome NVARCHAR(100) = (SELECT nome FROM inserted),
            @telefone NVARCHAR(30) = (SELECT telefone FROM inserted),
            @email NVARCHAR(100) = (SELECT email FROM inserted);

    /* continuação do script aqui... */

END

my question is this, is there any way I can make it declare without having to do 4 SELECT's? The question is more for optimization because it can surely be used in numerous other scripts...

  • Suggested reading: "Traps in the programming of trigger procedures" -> https://social.technet.microsoft.com/wiki/pt-br/contents/articles/38010.trappings-na-programm_procedure

1 answer

1


DECLARE @id BIT,
        @nome NVARCHAR(100),
        @telefone NVARCHAR(30),
        @email NVARCHAR(100);


SELECT @id = id,
       @nome = nome,
       @telefone = telefone,
       @email = email
  FROM inserted
  • 1

    Lol... honestly I didn’t think it was as simple as that...

Browser other questions tagged

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