为什么SQL Server无法正确显示sys.columns.object_id?

时间:2019-04-03 12:34:16

标签: sql-server-2016

当我仅从sys.columns.object_id获取sys.columns时,它显示以下结果:

select top 5 sys.columns.object_id as columns_object_id from sys.columns

columns_object_id
-----------
3
3
3
3
3

但是当我与sys.columns.object_id联接后获取同一列sys.tables.object_id时,将显示以下结果:

SELECT top 5 c.object_id as column_Object_id, t.object_id as Table_Object_id FROM sys.columns as c JOIN sys.tables as t ON c.object_id = t.object_id

column_Object_id Table_Object_id
---------------- ---------------
114099447        114099447
114099447        114099447
114099447        114099447
114099447        114099447
114099447        114099447

现在我想知道为什么columns.Object_id不能像联接查询中那样显示吗?

1 个答案:

答案 0 :(得分:1)

这里发生了几件事。

首先,sys.tables仅具有有关用户表的信息。您在第一个查询中看到的object_id是系统表,因此您的联接将过滤掉该表。

此外,SQL Server中的表是无序的数据集,如果没有随附的TOP(n)ORDER BY毫无意义。所以这也是它的一部分。

尝试这些变体,以了解我的意思。我显然有与您不同的用户表,因此我得到的结果对您来说毫无意义,但是您会在系统上看到它们之间的区别:

SELECT --Returns 3 for me, too.
  TOP 5
  OBJECT_NAME(object_id)
 ,c.object_id as columns_object_id
FROM
  sys.columns AS c;

SELECT --Returns the first user table's data.
  TOP 5
  OBJECT_NAME(c.object_id) AS ObjectName
 ,c.object_id as column_Object_id
 ,t.object_id as Table_Object_id
FROM
  sys.columns AS c
JOIN
  sys.tables AS t
    ON
    c.object_id = t.object_id;

现在尝试此操作,注意ORDER BYLEFT JOIN,因为我们要查找的系统表不在表sys.tables上:

SELECT
  TOP 5
  OBJECT_NAME(c.object_id) AS ObjectName
 ,c.object_id as column_Object_id
 ,t.object_id as Table_Object_id
FROM
  sys.columns AS c
LEFT JOIN
  sys.tables AS t
    ON
    c.object_id = t.object_id
ORDER BY c.object_id