tags:

views:

162

answers:

3

How to figure out if a table is in use in SQL (on any type database)? if somebody is already using it, or have it "open" then its in use.

+2  A: 

Check for open locks on the table.

Have a look on the syslockinfo table.

Chris Ballance
Thanks that lead me to the right answer: http://msdn.microsoft.com/en-us/library/ms190345.aspxFor MS SQL Server
igorgue
+4  A: 

Generally speaking, the correct way to find out whether someone else is using the table and will prevent you from doing whatever you want is to try doing what you want and to check whether it fails. If the failure message indicates 'non-exclusive access' or 'table in use' or equivalent, then you guessed wrong.

If your DBMS supports table locking, you can apply a lock to the table and then do a sequence of operations - but you'll impede other people who might otherwise be trying to use it.

Note that checking in a lock table (such as syslockinfo) is both DBMS-specific and unreliable - it leads to TOCTOU (time of check, time of use) problems.

Jonathan Leffler
A: 

Actually this will give you a better result:

select spid
    from master..sysprocesses
    where dbid = db_id('Works') and spid <> @@spid
igorgue
Is the double-dot correct notation?
Jonathan Leffler
yes it is, sorry I didn't see your comment
igorgue