Thursday, October 11, 2012

sql server script to know when the table accessed last time


If the database has lot many unwanted tables which are not being used by any of the applications and if you want to identify the ununused objects , so that you can remove or move those objects to a separate database , then the system view sys.dm_db_index_usage_stats (sql server 2008) contains the information with when the table accessed last time.
the script SQL-1 will produce the list of the tables which are being used and non-used as well. the records in the column [recent_datetime] contains the list of tables which are non been used since the server started.
Note : the counters on this DMV starts / refresh when the server is restarted.
-- Query-1
with cte_recent as
(
select SCHEMA_NAME(B.schema_id) +'.'+object_name(b.object_id) as tbl_name,
(select MAX(last_user_dt) from (values (last_user_seek),(last_user_scan),(last_user_lookup)) as all_val(last_user_dt)) as access_datetime FROM sys.dm_db_index_usage_stats a
right outer join sys.tables b on a.object_id =  b.object_id
)
select tbl_name,max(access_datetime) as recent_datetime  from cte_recent
group by tbl_name
order by recent_datetime desc , 1
output
image
To keep a track of the tables which are non been used , its better to store the results in a separate table and merge the table before restart the sql server or as per your own schedule as the SQL Server installed on cluster then you probably schedule it as a job to wait for an year before making the decision to remove or move those tables to a different database.
create a table TABLES_LAST_ACCESSED with 2 columns as below script
--Query-2
create table TABLES_LAST_ACCESSED (TBL_NAME VARCHAR(256),recent_datetime DATETIME)
sync the table with the script (Query-3) below
-- Query-3
with cte_recent as
(
select SCHEMA_NAME(B.schema_id) +'.'+object_name(b.object_id) as tbl_name,
(select MAX(last_user_dt) from (values (last_user_seek),(last_user_scan),(last_user_lookup)) as all_val(last_user_dt)) as access_datetime FROM sys.dm_db_index_usage_stats a
right outer join sys.tables b on a.object_id =  b.object_id
)
MERGE TABLES_LAST_ACCESSED AS target
USING (select tbl_name,max(access_datetime) as recent_datetime  from cte_recent group by tbl_name) AS source
ON (Target.tbl_name = Source.tbl_name)
when matched then
        UPDATE SET Target.recent_datetime = Source.recent_datetime
when not matched then
        INSERT (tbl_name,recent_datetime)VALUES (source.tbl_name,source.recent_datetime);
query any table by using select , insert , update or delete and execute the below statement. the tables which you accessed recently should be in the top.
SELECT * FROM  TABLES_LAST_ACCESSED ORDER BY 2 DESC
For more information on this DMV http://msdn.microsoft.com/en-us/library/ms188755.aspx




SQL Server 2005 : http://stackoverflow.com/questions/711394/how-do-you-find-the-last-time-a-database-was-accessed






15 comments:

  1. WHERE database_id = DB_ID()

    ReplyDelete
  2. The form, color, pattern, and composition of
    your abstract modern work of genius could even meet with you.
    marks that you've room to put an embroidery design prior to strip.
    In this course Graduates may enter or grow their skills within the professional
    world and employ the ability acquired to enhance their artistic or technical abilities.
    Details

    ReplyDelete
  3. Plans and surprises enhance your relationship using your distant partner.
    When you like to discover ways to meet women, one in the very first things you can learn is that you simply have to step out of your
    comfort zone. The important is, you realize how to just
    accept your mistake and request apology.Details

    ReplyDelete
  4. If your relationship is constructed of trust and honesty, it is certain that you simply along
    with your partner may have a very successful and lasting relationship.
    "We consider the latest Australian Property Monitors report to get information regarding the homes of your similar size have sold for in a set radius. Another in the signs your ex still likes you can be a quite more slight.

    ReplyDelete
  5. If your relationship consists of trust and honesty, you can be positive that you plus your partner will have a really successful and lasting relationship.
    Namely, there are millions upon countless individuals every day who
    spend time trying to find things on the Internet - then one of the things they search for could
    possibly be you. This is hard for some woman since everything now could be in long term and he or she has become aiming to
    have a very long and fulfilling relationship.

    ReplyDelete
  6. You can examine out of the image on normal paper to
    ascertain if it has the best size. A simple listing of
    his scientific and practical interests sounds incredible:
    anatomy, botany, cartography, geology, mathematics,
    aeronautics, optics, mechanics, astronomy, hydraulics, acoustics, civil engineering, designing weapons, urban planning
    and more. The character in the picture is filled with touching vitality and seems like a real
    part of front individuals .

    ReplyDelete
  7. He once acted since the art director of Republic Education and
    Culture Committee in the Jacobin dictatorship and played an important role in the politics.
    The most frequent examples in this field are televisions, comic books,
    magazines, digests, etc. In fact, holiday goers who consider gonna
    Oban choose wildlife trips since they would like to
    get a glimpse of what this place is capable of offering. Details

    ReplyDelete
  8. Giá Xe Chevrolet 24/7
    địa chỉ: Số 5, Ngọc Hồi, Hoàng Liệt, Hoàng
    Mai, Hà Nội
    SĐT: 09876.125.26
    Email: giaxechevrolet247@gmail.com

    Greetings! I know this is somewhat off topic but I was wondering if you knew where I could locate a captcha plugin for my
    comment form? I'm using the same blog platform as yours and I'm
    having problems finding one? Thanks a lot!

    ReplyDelete
  9. Closing in on 300! That definitely appeals to me.

    ReplyDelete
  10. Giá Xe Chevrolet 24/7
    địa chỉ: Số 5, Ngọc Hồi, Hoàng Liệt, Hoàng Mai,
    Hà Nội
    SĐT: 09876.125.26
    Email: giaxechevrolet247@gmail.com

    Hmm it seems like your blog ate my first comment (it was extremely long)
    so I guess I'll just sum it up what I wrote and say, I'm thoroughly enjoying
    your blog. I as well am an aspiring blog writer but
    I'm still new to everything. Do you have any recommendations for inexperienced blog writers?
    I'd definitely appreciate it.

    ReplyDelete
  11. Wow! After all I got a website from where I be capable of truly get valuable facts concerning my study and
    knowledge.

    ReplyDelete
  12. Excellent site you have got here.. It's difficult to find excellent writing like yours nowadays.
    I really appreciate people like you! Take care!!

    ReplyDelete
  13. Hello! I've been reading your blog for a long time now annd finally
    got the courage to go ahead and give you a shhout out from Kingwood Texas!

    Just wanted to mention keep up the fanntastic job!

    ReplyDelete
  14. Hi to every one, it's really a good for me to go to see this site, it contains valuable Information.

    ReplyDelete
  15. Thanks for some other great article. The place else could anyone get that type of info in such an ideal manner of writing?
    I have a presentation next week, and I'm
    on the look for such information.

    ReplyDelete

Featured Post

SQL Server AWS Migration BCP

stored procedure to generate BCP scritps to migrate the SQL Server database. Developed this stored procedure on my labs to simulate t...

Contributors