SQL dot notation

前端 未结 3 814
孤城傲影
孤城傲影 2020-11-29 06:54

Can someone please explain to me how SQL Server uses dot notation to identify
the location of a table? I always thought that the location is Database.dbo.Table

3条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 07:25

    What @Szymon said. You should also make a point of always schema-qualifying object references (whether table, view, stored procedure, etc.) Unqualified object references are resolved in the following manner:

    • Probe the namespace of the current database for an object of the specified name belonging to the default schema of the credentials under which the current connection is running.

    • If not found, probe the namespace of the current database for an object of the specified name belonging to the dbo schema.

    And if the object reference is to a stored procedure whose name begins with sp_, it's worse, as two more steps are added to the resolution process (unless the references is database-qualified): the above two steps are repeated, but this time, looking in the database master instead of the current database.

    So a query like

    select *
    from foo
    

    requires two probes of the namespace to resolve foo (assuming that the table/view is actually dbo.foo): first under your default schema (john_doe.foo) and then, not being found, under dbo (dbo.foo'), whereas

    select *
    from dbo.foo
    

    is immediately resolved with a single probe of the namespace.

    This has 3 implications:

    1. The redundant lookups are expensive.

    2. It inhibits query plan caching, as every execution has to be re-evaluated, meaning the query has to be recompiled for every execution (and that takes out compile-time locks).

    3. You will, at one point or another, shoot yourself in the foot, and inadvertently create something under your default schema that is supposed to exist (and perhaps already does) under the dbo schema. Now you've got two versions floating around.

      At some point, you, or someone else (usually it happens in production) will run a query or execute a stored procedure and get...unexpected results. It will take you quite some time to figure out that there are two [differing] versions of the same object, and which one gets executed depends on their user credentials and whether or not the reference was schema-qualified.

    Always schema-qualify unless you have a real reason not to.

    That being said, it can sometimes be useful, for development purposes to be able to maintain the "new" version of something under your personal schema and the "current" version under the 'dbo' schema. It makes it easy to do side-by-side testing. However, it's not without risk (which see above).

提交回复
热议问题