开发者

Find tables name in multi-part identifier

I’m trying to select various table and column names from a (SQL Server 2008) database. The database is fairly big. There are several databases sitting on the same server, each with various schemas etc. Once there’s a multi-part identifier involved I’m stuck. For example, to retrieve a list of tables in under a database this works fine:

SELECT [name]
FROM DatabaseOne.sys.tables
ORDER BY [name]

Then I want to get the tables under a certain schema. E.g.:

SELECT [name]
FROM DatabaseOne.SchemaOne.sys.tables
ORDER BY [name]

But I get the error:

Could not find server 'DatabaseOne' in sys.servers. Verify that the correct server name was specified. If necessary, execute the stored procedure sp_addlinkedserver to add the server to开发者_如何学运维 sys.servers.

A large part of the problem probably lies in the fact that I don’t really know anything about schemas (if that’s even what they are).

Also, if I want to find the column names in a table, say DatabaseOne.SchemaOne.TableOne, how would I go about doing that?

Any help would be highly appreciated.


If you use a four part name, SQL Assumes the first portion is the name of a linked server.

The system tables are in the sys schema, and contain data for all other schemas like dbo or whatever.

In sys.tables there is a schema_id value that specifies which schema each table is in. There is also a sys.schemas table which contains the schemas.

If you know your schema name, you can do a

SELECT [name]
FROM DatabaseOne.sys.tables t
INNER JOIN sys.schemas s
    ON s.schema_id = t.schema_id
WHERE s.name = 'MySchema'
ORDER BY [name]

You can also check multiple schemas by making the s.name evaluation an IN evaluation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜