简体   繁体   中英

SQL: insert row with expiration

Is there a way to insert a row into SQL with an expiration (cf you can insert a new key that expires in a minute with Memcached)?

The context is that I want an integration test to insert rows into a database, but I'd prefer not deleting them myself, as it's shared by many. Those delete queries must be manual, or they may not be run, or they may have disastrous typos, etc. I'd prefer the system to do it for me if it can (ie automatically and efficiently and well-tested).

(I assume this is not part of the SQL standard and the answer is no.)

related: SQL entries that expire after 24 hours

related: What is the best way to delete old rows from MySQL on a rolling basis?

CONTEXT: I can't make any changes to the database schema, or any of the associated infrastructure.

If you were doing unit testing, I would suggest wrapping each unit test in a BEGIN TRAN / ROLLBACK .

Since you are doing integrated testing, you probably need the data to live outside the scope of a single transaction. SQL Agent would work fine here, except that it would not distinguish between test data and real data. However, you could get around this by INSERT ing some identifier to the specific records to be deleted upon expiration. That could be done in a single stored proc..

You might be able to accomplish this by using SQL Server Service Broker . I have not worked with the service broker, but maybe there is a way to delay message processing until a specific time has passed.

add an expiration date column to your table(s). create a job that will delete data that is past expiration on some schedule (say nightly).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM