Need to capture database name when error occurs with sp_msforeachdb

微笑、不失礼 提交于 2019-12-24 15:35:15

问题


I am running a dynamic sql command with sp_msforeachdb for each database. However the command bombs for a certain database.

How is '?' used to display the database name when the error happens? I tried using it in a Catch statement but my syntax is wrong.


回答1:


Just use DB_NAME()

EXEC sp_msforeachdb 'USE ? SELECT DB_NAME() ...do stuff'



回答2:


It worked to me:

exec sp_MSforeachdb 'select *, print ''?'' from TABLE'



回答3:


Depending on the script, you get for all db's the ouput "master" with DB_NAME().
You can use DB_NAME(DB_ID(''?'')) in these cases:

exec sp_msforeachdb 'select DB_NAME(DB_ID(''?'')), Value from ?.dbo.MyTable WHERE(ColumnX = N''1'')'

which would result in something like this:

+-------------+-------+
| DBLegacy | VA1 |
+-------------+-------+
+-------------+-------+
| DBNew12 | ABC |
+-------------+-------+
+-------------+-------+
| DBOld333 | XYZ |
+-------------+-------+

To get the results into one result set see: SQL Server: sp_MSforeachdb into single result set
This would result in this:

+-------------+-------+
| DBLegacy | VA1 |
+-------------+-------+
| DBNew12 | ABC |
+-------------+-------+
| DBOld333 | XYZ |
+-------------+-------+



来源:https://stackoverflow.com/questions/3808338/need-to-capture-database-name-when-error-occurs-with-sp-msforeachdb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!