Need to capture database name when error occurs wi

2019-07-31 16:39发布

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.

3条回答
走好不送
2楼-- · 2019-07-31 16:41

Just use DB_NAME()

EXEC sp_msforeachdb 'USE ? SELECT DB_NAME() ...do stuff'
查看更多
何必那么认真
3楼-- · 2019-07-31 16:45

It worked to me:

exec sp_MSforeachdb 'select *, print ''?'' from TABLE'
查看更多
淡お忘
4楼-- · 2019-07-31 16:59

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 |
+-------------+-------+

查看更多
登录 后发表回答