Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate the underlying table in a view

I'm currently in a situation where we are creating a "facade" database which basically consists of a set of views which are simply a select from an identically named table in another database. The idea is that the application can be repointed to the facade database with minimal changes to the actual code.

This seems to work ok for inserts, update, deletes, and obviously selects. Unfortunately, some of the stored procedures use TRUNCATE TABLE in places. It's very limited and our plan right now is to just replace that code with a call to a "TRUNCATE" stored procedure which will actually handle the table truncation behind the scenes. Before going forward with that though, I wanted to see if there were any other suggestions on how to handle this.

Thanks for any suggestions or advice!

like image 973
Tom H Avatar asked May 24 '10 15:05

Tom H


People also ask

Can you truncate a table in a view?

You cannot use the truncate command with the indexed views. Delete command retains the object statistics and allocated space. Truncate deallocates all data pages of a table. Therefore, it removes all statistics and allocated space as well.

How do I truncate data from a SQL view?

TRUNCATE TABLE removes all rows from a table, but the table structure and its columns, constraints, indexes, and so on remain. To remove the table definition in addition to its data, use the DROP TABLE statement.

Can truncate table participate in indexed view?

Answers. As you have discovered, you cannot truncate a table that is referenced by an indexed view.

How do you truncate a table?

The SQL TRUNCATE TABLE command is used to delete complete data from an existing table. You can also use DROP TABLE command to delete complete table but it would remove complete table structure form the database and you would need to re-create this table once again if you wish you store some data.


1 Answers

Your approach (using special stored procedures) is the only way the do it because TRUNCATE TABLE (Transact-SQL) only works on tables, not views. I guess you have a specific reason (faster and uses fewer system and transaction log resources) to use TRUNCATE over DELETE, since you have the DELETEs working on the views. You might be able to do something with a DELETE trigger, and detect if all rows are being removed use a truncate. I think you approach with a stored procedure is the cleanest way to go.

like image 57
KM. Avatar answered Sep 21 '22 01:09

KM.