Search code examples
sqlsql-servert-sqlsql-insertdatabase-trigger

Automatically fill row with value based on inserted id


I have a table where the user is able to insert the ID of a Node that corresponds to a title elsewhere in the database. I want this tile to be automatically inserted into the row after the user has chosen the id.

This is my table: enter image description here

I need to have the "SommerhusNavn" column be automatically filled with values based on the "SommerhusId" inserted.

I am using a third party to handle the CRUD functionality, where the user picks the ID from a dropdown. I already know in which table the title for the ID is located, I'm just not sure how to fill the row with the insert statement. Would I need to run a separate query for this to happen?

Edit:Solution

CREATE TRIGGER [dbo].[BlokeredePerioderInsert]
ON  dbo.BlokeredePerioder
AFTER INSERT
AS 
BEGIN   
SET NOCOUNT ON;

UPDATE BlokeredePerioder SET SommerhusNavn = text FROM umbracoNode AS umbNode
where SommerhusId = umbNode.id

END
GO

Solution

  • Yes, you need to run additional UPDATE query. Let's assume that you have the TitlesTable, with columns ID and Title. Then it should look like:

    UPDATE MyTable SET SommerhusNavn = Title FROM TitlesTable AS A
    WHERE SommerhusId = A.ID
      AND SommerhusNavn IS NOT NULL --not necessary