zaagan
8/21/2019 - 3:36 PM

MS SQL DB Utils

MS SQL DB Utils

-- MODIFY DB NAME 1
Alter Database MyDb 
Modify Name = MySecondDb;

-- MODIFY DB NAME 2
Execute sp_renameDB 'OldDBName', 'NewDBName'

-- LIST DBS
SELECT * FROM sys.databases;
SELECT * FROM sys.databases WHERE name='dbName';

-- LIST SERVERS
SELECT * FROM sys.servers;

-- DROP AND RE-CREATE DB
use master
IF EXISTS( select * 
             from sys.databases 
             where name = 'DB-Name')
DROP DATABASE DB-Name
CREATE database DB-Name

-- ADD USER TO DB
USE DatabaseName
GO
sp_adduser 'loginUser'


-- LIST ALL USERS AND ROLES
SELECT dp.NAME AS principal_name,
       dp.type_desc AS principal_type_desc,
       o.NAME AS object_name,
       p.permission_name,
       p.state_desc AS permission_state_desc
FROM   sys.database_permissions p
LEFT   OUTER JOIN sys.all_objects o
ON     p.major_id = o.OBJECT_ID
INNER  JOIN sys.database_principals dp
ON     p.grantee_principal_id = dp.principal_id


-- ADD COLUME TO EXISTING TABLE WITH DEFAULT VALUE
ALTER TABLE {TABLENAME}
ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL}
CONSTRAINT {CONSTRAINT_NAME} 
        DEFAULT {DEFAULT_VALUE}[WITH VALUES]

-- SHOW STORED PROCEDURE CODE
sp_helptext SP_NAME