Proper query

Igor Korot 56 Reputation points
2025-01-15T06:50:47.5833333+00:00

Hi, ALL,

Right now I'm using following query

SELECT object_id FROM sys.objects o, sys.schemas s WHERE s.schema_id = o.schema_id AND o.name = ? AND s.name = ?

Is there a simple way to bring in sys.databases table?

Thank you.

EDIT:

Let me clarify this further as it seems the way its written is confusing...

When I connect to the DB thru the ODBC/C++ I have a database to connect to.

After that it is possible to bring in another database on same connection - either by using ATTACH or from CREATE DATABASE (as I think after it is created I will automatically be connected to it).

So, lets say I ran SQLDriverConnect() and got a successful connection. The DB name is "current_draft". Now later on I ran SQLExecDirect( stmt, "ATTACH last_year_draft".

When I run the "ATTACH..." command which, presumably succeed I need to retrieve the table info from that newly attached DB.

The function signature is:

GetTableId(const std::wstring &catalog, const std::wstring &schema, std::wstring &table, long &tableId, std::vectorstd::wstring &errors)

I hope it is now better and I get a good respnce on what and how to modify my query

Thank you.

SQL Server Other
{count} votes

3 answers

Sort by: Most helpful
  1. 博雄 胡 685 Reputation points
    2025-01-15T07:09:43.9866667+00:00

    easy

    SELECT object_id,apply1.* FROM sys.objects o, sys.schemas s cross apply(select * from sys.databases d where d.database_id = db_id())apply1 WHERE s.schema_id = o.schema_id AND o.name = ? AND s.name = ?
    

  2. Dan Guzman 9,401 Reputation points
    2025-01-15T17:52:54.68+00:00

    The sys.objects and sys.schemas catalog views are scoped to the current database (only objects in the current database context are returned). Simply add DB_NAME() to the result to return the current database name in the result set. No additional joins are needed. The below example uses the newer ANSI-92 explicit join syntax:

    SELECT object_id, DB_NAME() AS database_name

    FROM sys.objects o

    JOIN sys.schemas s ON s.schema_id = o.schema_id

    WHERE o.name = ? AND s.name = ?;


  3. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2025-01-15T22:27:06.66+00:00

    If I understand your edit to the post, you simply want to run

    SELECT object_id FROM nameofdbhere.sys.objects o, nameofdbhere.sys.schemas s WHERE s.schema_id = o.schema_id AND o.name = ? AND s.name = ?
    
    
    

    The query would need to have the DB name hardcoded, but since you seem to generate this query from the client, that should not be an issue.

    Just have an unnerving feeling that I still don't understand your problem...


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.