Monday, November 21, 2016

T-SQL code to get the active Connections for each Database.

--Method 1
 SELECT 
    DB_NAME(dbid) as DBName, 
    COUNT(dbid) as NoOfConnections,
    loginame as LoginName
FROM
    sys.sysprocesses
WHERE 
    dbid > 0
GROUP BY 
    dbid, loginame


--Method 2
EXEC sp_who2


--Method 3
SELECT  spid,
        sp.[status],
        loginame [Login],
        hostname, 
        blocked BlkBy,
        sd.name DBName, 
        cmd Command,
        cpu CPUTime,
        physical_io DiskIO,
        last_batch LastBatch,
        [program_name] ProgramName   
FROM master.dbo.sysprocesses sp 
JOIN master.dbo.sysdatabases sd ON sp.dbid = sd.dbid
ORDER BY DBName,spid

Wednesday, November 16, 2016

Delete all Tables based on creation date


--Delete all Tables based on creation date



 DECLARE @tname VARCHAR(100)
DECLARE @sql VARCHAR(max)

DECLARE db_cursor CURSOR FOR
SELECT name AS tname
FROM sys.objects
WHERE create_date < GETDATE() - 1-- Days old

OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @tname

WHILE @@FETCH_STATUS = 0
BEGIN
       SET @sql = 'DROP TABLE ' + @tname
       --EXEC (@sql)  -- For Executing
       PRINT @sql --For Printing

       FETCH NEXT FROM db_cursor INTO @tname
END

CLOSE db_cursor
DEALLOCATE db_cursor

Friday, November 4, 2016

Simplest way to Truncate/Delete all tables in a given database.


Simplest way to Truncate all tables in a given database.
Use databasename
EXEC sp_MSForEachTable 'Truncate TABLE ?' --- For Truncating all tables



Simplest way to Truncate all tables in a given database.
Use databasename
EXEC sp_MSforeachtable @command1 = "DROP TABLE ?"  --- For Deleting all tables