Tuesday, December 23, 2014

Disconnect/Kill all the SPID's in the database

Some times a situation like to restore the database immediately.
When you are trying to do that, It will not let you install and throwing the error saying Database is in use....
Once you find the SPID's running under the database, It may be hard to disconnect all of them in single short (Of course you can use Single user mode, It has its own problems though).

By running the following script you can kill all the SPID's running under the desired database and you can restore the database by adding restore database script.
Please take a look at it,


DECLARE @ID INT
DECLARE @MSG CHAR(8), @DataName SYSNAME = 'newdb'

WHILE 1 = 1
BEGIN
 SET ROWCOUNT 1
 SELECT  @id = spid
        FROM Master..Sysprocesses P,
                Master..Sysdatabases D
         WHERE D.Name=@DataName AND
                D.dbid = P.dbid
IF @@rowcount = 0
 BREAK

 SELECT @msg = 'KILL ' + CONVERT(CHAR(8) ,@ID)

PRINT @msg
EXEC( @msg)

END

-- Please continue your restore script here.

Tuesday, December 9, 2014

How can we stop pulling data from a table in SQL server ?

It looks funny when you think about it but its true.
One of the way  you can stop users to pull data from a table is not a Heap should be disable Cluster Index.

If you disable the Cluster Index as it has the data, You can't be accessible though you hold required permissions.

ALTER INDEX IndexName ON TableName DISABLE.

How to find all the users in my windows group?

 You have an extended stored procedure to get the information, which you have requested.

xp_logininfo 'Your windows Group','members'

Database Read_Only Vs Read_Write

Some times, You may get a situation like need to make your database as read_only time being...
Please follow the below..

If you want to make you database set to read only from (READ_WRITE) Normal DB,Then you can follow below
Note: Conditions apply, You will have to disconnect users from respected database.
USE [master]
GO
ALTER DATABASE [DatabaseName] SET  READ_ONLY WITH NO_WAIT
GO
If you want to make your database set to REGULAR(READ and WRITE), Then you can follow below...
Note: Conditions apply, You will have to disconnect users from respected database.

USE [master]
GO
ALTER DATABASE [DatabaseName] SET  READ_WRITE WITH NO_WAIT
GO