引言:
我们在做较新的Java项目时,如果数据库添加了索引,出错后,会在Java侧捕获到这些异常信息。特别是数据库索引命名很“丑”的情况下,看着所报的“索引index_A(或者唯一索引index_A)冲突”,就只好一个个表猜着找。其实在sqlServer下,可以通过SQL语句直接用这个所报的索引名称“index_A”查出所属表。
正文:
sqlServer下,根据索引名查询所属表名,可以采用如下SQL语句:
--------------------------------------------
-- search the table name by an index name
--------------------------------------------
-- define the index's name
DECLARE @index_name NVARCHAR(200)
-- set the index_name here
SET @index_name = N'PK__FILE_TABLE_REL__208E6DA8';
SELECT o.name
FROM sys.objects o
WHERE o.object_id = (SELECT s.object_id
FROM sys.stats s
WHERE s.name = @index_name)
特别是在表很多的情况下,相当方便。