Unable to perform delete on View SQL Server 2005

后端 未结 3 739
时光说笑
时光说笑 2021-01-29 05:01

I am unable to perform a delete on a View. Everything worked fine on the individual tables.

EDIT1: Added Trigger

CREATE TRIGGER myTrigger
ON [ViewName]
I         


        
3条回答
  •  深忆病人
    2021-01-29 05:23

    Okay, let's imagine one instance where this error will occur (since you haven't shown your view definition).

    Let's assume we have a view:

    CREATE VIEW dbo.V1
    with schemabinding
    as
        select 'T1' as TabName,T1ID as ID,ImportantDate from dbo.T1
        union all
        select 'T2',T2ID,ImportantDate from dbo.T2
    

    is we now attempt:

    DELETE from dbo.V1 where ImportantDate < DATEADD(day,-90,CURRENT_TIMESTAMP)
    

    we'll get the error you've shown (or similar). So what we need is a trigger:

    CREATE TRIGGER T_V1_D
    on dbo.V1
    instead of delete
    as
        set nocount on
        delete from dbo.T1 where T1ID in (select ID from deleted where TabName = 'T1')
        delete from dbo.T2 where T2ID in (select ID from deleted where TabName = 'T2')
    

    This trigger gets considerably more complex to write if there's no easy way to correlate rows from the deleted psuedo-table with which rows need to be deleted from each base table.

提交回复
热议问题