Why can't SQL Server alter a view in a stored procedure?

后端 未结 1 1923
萌比男神i
萌比男神i 2020-12-18 07:31

I\'m using MS SQL Server, and I\'d like to alter a view from within a stored procedure, by executing something like \"alter view VIEWNAME as ([some sql])\".

A few pa

1条回答
  •  情话喂你
    2020-12-18 07:54

    I think the answers are:

    1. MS want to prevent DDL being run from within procedures.
    2. The code within the exec statement is not treated as part of the procedure - so it is not subject to the same restrictions as the procedure.
    3. No.

    An alternative approach might be to have a separate table (called something like swing_table) with either 1 or 0 records to indicate whether the view should query the production or other (backup?) table respectively - something like:

    create view viewname as
    select {field list}
    from production_table
    cross join swing_table
    union all
    select {field list}
    from backup_table
    where (select count(*) from swing_table) = 0
    

    - then TRUNCATE swing_table within the procedure when you want to, erm, swing the table - since TRUNCATE is not a transactional command, it should execute immediately.

    0 讨论(0)
提交回复
热议问题