MSSQL: common query to manipulate a database

Check database’s properties:

sp_helpdb;  --check all database

USE db_name;
GO
sp_helpdb db_name;


Check database space usage:

USE db_name;
GO
EXEC sp_spaceused;


Check current database collation:

SELECT name, collation_name FROM sys.databases WHERE name=N'db_name';
--or
SELECT CONVERT (varchar(256), DATABASEPROPERTYEX('db_name','collation'));


Change database collation:

ALTER DATABASE [db_name] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
ALTER DATABASE [db_name] COLLATE [collation_name];
GO
ALTER DATABASE [db_name] SET MULTI_USER;
GO


Change database owner:

USE db_name;
GO
EXEC sp_changedbowner 'db_login';


Shrink database manually:

must read: docs

USE db_name;
GO
DBCC SHRINKDATABASE(db_name, 10);    --shrink with rest percent

DBCC SHRINKFILE(db_name, 10);    --shrink with rest megabyte


Fix "Recovery Pending" status:

ALTER DATABASE [DB_name] SET EMERGENCY;
GO
ALTER DATABASE [DB_name] set single_user
GO
DBCC CHECKDB ([DB_name], REPAIR_ALLOW_DATA_LOSS) WITH ALL_ERRORMSGS;
GO
ALTER DATABASE [DB_name] set multi_user
GO


Take offline or bring online a database:

ALTER DATABASE [DB_name] SET OFFLINE
--
ALTER DATABASE [DB_name] SET ONLINE

 

Find a column name

SELECT      c.name  AS 'ColumnName'
            ,t.name AS 'TableName'
FROM        sys.columns c
JOIN        sys.tables  t   ON c.object_id = t.object_id
WHERE       c.name LIKE '%MyName%'
ORDER BY    TableName
            ,ColumnName;


Reference: SQL Server technical documentation - SQL Server | Microsoft Docs

创建时间:6/25/2022 8:23:24 PM 修改时间:4/12/2023 1:55:37 PM