将新行添加到表后动态创建视图

时间:2013-02-01 09:42:40

标签: sql-server view database-trigger

我有一个包含4个表的数据库

- 电池 -细胞 -owner

每个电池都有多个电池和一个所有者。

单元格表将包含大量条目。 我想要一个触发器,为每个显示电池信息及其电池信息的新电池创建视图。

我有一个postgre sql触发器,运行得很好(感谢stackoverflow :)):

    BEGIN

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

RETURN NEW;

END;

但我无法将其转置到SQL服务器,我绝对不知道如何做到这一点。

这是我的数据库的简单图表:

DB Diagram

所以最后每个新电池我都需要用它的单元来查看它。

Ps:对不起,如果我的英语不流利:/

1 个答案:

答案 0 :(得分:1)

希望这能指出你正确的方向......

   /*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