为什么我不能在SQL视图中查询单个列?

时间:2015-12-10 19:30:19

标签: sql sql-server view

我使用了一个脚本来创建一个视图,该视图具有数据库中每个表的表名,以及相应表中的数据行数。 SELECT *一切正常。但是,我只想查询某些行,但我似乎无法这样做。

视图是使用以下脚本创建的(脚本为DatabaseZone.com):

CREATE VIEW RowCount_AllTables 
AS
    SELECT DISTINCT
        sys.schemas.name, sys.tables.name AS tableName, 
        sys.dm_db_partition_stats.row_count AS 'RowCount'
    FROM 
        sys.tables 
    INNER JOIN
        sys.dm_db_partition_stats ON sys.tables.object_id = sys.dm_db_partition_stats.object_id 
    INNER JOIN
        sys.schemas ON sys.tables.schema_id = sys.schemas.schema_id
    WHERE     
        (sys.tables.is_ms_shipped = 0)

当我针对生成的视图运行Select *时,我得到的结果如下:

name    tableName     RowCount
dbo     Table1          2
dbo     Table2          1230
dbo     Table3          0

如果我只查询tableName列,那么工作正常并返回表名。但是,如果我也尝试查询RowCount列,则会收到错误消息Incorrect syntax near the keyword 'RowCount。无论我是否限定数据库,都会发生这种情况 - 它似乎无法将RowCount识别为我可以在查询中调用的有效列。所以这个脚本失败了:

SELECT RowCount 
FROM RowCount_AllTables;

但是这个有效:

SELECT tableName 
FROM RowCount_AllTables;

发生了什么事?我希望能够在查询中为视图中的列名设置别名,但只要我无法引用RowCount列,我就无法做到。

(仅供参考,在SQL Server 2014中运行)

2 个答案:

答案 0 :(得分:1)

Rowcount是保留字,您可以使用[] as:

选择保留字
[Rowcount]

答案 1 :(得分:0)

感谢@sgeddes指出方向。删除了视图,更改了创建它的脚本以使用行计数列的其他名称,现在它按预期工作。问题是Rowcount是一个保留字的冲突。

更改了此行上的create table脚本:

SELECT  distinct  sys.schemas.name, sys.tables.name AS tableName,
 sys.dm_db_partition_stats.row_count AS 'RowCount'

为:

SELECT  distinct  sys.schemas.name, sys.tables.name AS tableName,
 sys.dm_db_partition_stats.row_count AS 'Row_Count'

...此时我现在可以根据需要引用Row_Count列。