This article introduces two stored procedures that are very useful in the master database but not mentioned in SQL Server online textbooks.
These
System The process is very convenient for processing the following tasks, such as determining the storage space used, the number of rows, and the user table index. In the first process, sp_msforeachdb executes three commands for each database on the server of interest. @ Command1: The first command to be executed @ replacechar: Replace "?" With another placeholder @ Command2: The second command to be executed @ command3: The third command to be executed @ precommand: the command to be executed before entering the loop @ postcommand: after the loop ends, each command set (even if the set contains only one command) is executed as a batch for each database, this is useful when we want to output the captured results to the text instead of the standard result set table. To achieve this, select the query button in the menu | output result | output to text or press the shortcut key [CTRL] T. The following
Code Return the number of user data tables in each database on the server:
Exec sp_msforeachdb @ command1 = "use? Exec sp_spaceused"
The abbreviated output looks like this: the brief output may be as follows: database Name database size unallocated space size slave master 5.25 mb1.26 MB reserved data index_size unused ---------------- -------------------- 2808 kb 1144 kb 1080 kb 584 kb second process sp_msforeachtable accept 7 parameters: @ command1: the first command to be executed @ replacechar: Replace "?" @ Command2: The second command to be executed @ command3: The third command to be executed @ whereand: where Condition Statement (or order by statement) @ precommand: the command to be executed before the loop @ postcommand: after the loop ends, you can skip the Null Value Transfer Requirement by naming the parameters to be passed. The @ replacechar parameter is very useful when the command to be executed contains a question mark. The implementation of the @ whereand parameter can narrow the output range according to the filter. You can also add an order by statement. In the following example, the number of rows in each data table in the adventureworks database is returned and sorted by data indication:
Exec sp_msforeachtable @ command1 = "print '? '",
@ Command2 = "select count (*) from? ", @ Whereand =" order by 1"
The output result is as follows:
[HumanResources]. [Department] -----------
16 [HumanResources]. [employee] ----------- 290 [HumanResources].
[employeeaddress] ----------- 290 [HumanResources].
[employee1_menthistory] ----------- 296 This article is from 51cto. com technical blog