Question

I have a database wich contain 4 tables

-battery -cell -owner

each battery have multiple cell and one owner.

The cell table will contain a tons of entry. i wanted a trigger that create view for each new battery that display the battery information and its cell's information .

I had a postgre sql trigger that worked kinda well (thanks to stackoverflow :) ) :

    BEGIN

EXECUTE $$CREATE OR REPLACE VIEW battery_vue
AS
SELECT * FROM cells WHERE battery_serial = $$ || NEW.battery_serial;

RETURN NEW;

END;

but i'm unable to transpose it to SQL server and i have absolutly no clue on how to do it.

here is a simple diagram of my database :

DB Diagram

So at the end for each new battery i need a view of it with its cells.

Ps : sorry if my english is not fluent :/

Was it helpful?

Solution

Hopefully this points you in the right direction...

   /*Create a test table*/
IF OBJECT_ID('TestBattery') IS NOT NULL
BEGIN
    DROP TABLE dbo.[TestBattery]
END
GO

CREATE TABLE dbo.[TestBattery]
(
id          INT
,owner_id    INT
,data_id     INT
)
GO

/*Create a test trigger*/
IF OBJECT_ID('trg_TestBattery_CreateView') IS NOT NULL
BEGIN
    DROP Trigger dbo.trg_TestBattery_CreateView
END
GO


CREATE TRIGGER [dbo].[trg_TestBattery_CreateView]
ON [dbo].[TestBattery] AFTER INSERT
AS
SET NOCOUNT ON 

DECLARE @BatteryID      INT
        ,@View          VARCHAR(200)
        ,@SQLCreateView VARCHAR(MAX)

SELECT @BatteryID = ID FROM INSERTED

/*Dynamically generate new view name based on BatteryID that was inserted*/
SELECT @View = 'TestBattery_'+CAST(@BatteryID AS VARCHAR)

/*Generate SQL to create the view*/
SELECT @SQLCreateView = 'CREATE VIEW '+@View+' AS SELECT [id],[owner_id],[data_id] FROM dbo.[TestBattery] WHERE ID = '+CAST(@BatteryID AS VARCHAR)

/*We create the view only if it doesn't exist*/
IF OBJECT_ID(@View) IS NULL
BEGIN

EXEC(@SQLCreateView)

END
GO

/*Testing your trigger*/
INSERT INTO TestBattery
(
id
,owner_id
,data_id
)
SELECT
'1'
,'2'
,'3'

SELECT * FROM TestBattery
SELECT * FROM TestBattery_1

/*Take out the trash*/
DROP TABLE TestBattery
DROP VIEW TestBattery_1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top