SQL触发器在视图上插入到表中

时间:2014-09-23 05:56:34

标签: sql-server tsql

我试图在如下所示的视图上设置插入触发器:

CREATE view [dbo].[PYC_ServiceAppointments] AS   
   SELECT 
      e.epUR as 'ClientUR',  
      codeDescription as 'Category',  
      s.serName as 'Service',  
      a.OccurrenceDate as 'StartDate',   
      a.EndDate as 'EndDate',   
      a.StartTime as 'StartTime',   
      a.EndTime as 'EndTime',   
      a.Confirmed as 'ServiceStatus', 
      a.Note as 'Note'   
   FROM  
      [ServiceAppointmentViewBase] a  
   INNER JOIN 
      Episode e ON e.cid = a.ClientID AND e.epRecent = '1' 
   INNER JOIN 
      [Service] s ON s.serID = a.ServiceID 
   LEFT JOIN 
      Codes c ON s.sCatCode = c.codecode AND c.codetype = 'SVC'  

我使用下表作为要插入数据的表格:

CREATE TABLE [dbo].[ServiceAppointments]
(     
    [SID] [int] IDENTITY(1,1) NOT NULL,    
    [ClientUR] [varchar](50) NULL,      
    [Category] [varchar](150) NULL,         
    [Service] [varchar](60) NULL,     
    [StartDate] [datetime] NULL,      
    [EndDate] [datetime] NULL,       
    [StartTime] [datetime] NULL,     
    [EndTime] [datetime] NULL,  
    [ServiceStatus] [bit] NULL,     
    [Note] [text] NULL, 

    PRIMARY KEY CLUSTERED ([SID] ASC)    
      WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,     
            ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 
) ON [PRIMARY] 
TEXTIMAGE_ON [PRIMARY]      

这是我试图用来执行插入的触发器:

 CREATE TRIGGER [dbo].[Trigger_Service]
 ON [PYC].[dbo].[PYC_ServiceAppointments]
 INSTEAD OF INSERT
 AS 
 BEGIN
    SET NOCOUNT ON;
    SET ROWCOUNT 0;

    INSERT INTO PYC.dbo.ServiceAppointments 
               ( 
                ClientUR,
                Category,
                [Service],
                StartDate,
                EndDate,-- = ISNULL(Getdate(), CurrentValues.EndDate)),
                StartTime,
                EndTime,
                ServiceStatus,
                Note )
        SELECT  
           b.ClientUR, b.Category, b.[service], b.StartDate, b.EndDate, 
           b.StartTime, b.EndTime, b.ServiceStatus, b.Note
        FROM    
           Inserted b   
END             

存储数据的数据库没有针对表的唯一ID,所以我想要完成的是在数据库中添加一个条目并在视图中满足要求时它将填充此条目,它将触发触发器并将此行添加到表中,并使用SID(PK)为该行分配id。

我在包含与指定表格相同的列的测试表上尝试了相同的触发器,当条目添加到表格时,触发器将触发并将该行添加到另一个表格。

我使用触发器相当新,所以任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:1)

如果我理解正确,问题是如果您将数据插入ServiceAppointmentViewBase表,则触发器不起作用。这是正确的行为。您的触发器在视图上定义,因此仅当您通过此视图插入数据时才会触发该触发器。如果在不使用视图PYC_ServiceAppointments的情况下将数据直接插入表中,则不会触发它。当然,要通过视图插入数据,它必须是可更新的,或者当marc_s指向时,此视图上必须存在而不是触发器(如您的情况)。