运行存储过程时,我不断收到此错误:
列'#objects.TableName'在选择列表中无效,因为它既不包含在聚合函数中,也不包含在GROUP BY子句中。
我理解错误本身,但是在我的情况下这是没有意义的,因为临时表本身没有任何聚合,而且我在另一个存储过程中包含此确切的临时表,并且该表在没有问题。临时表的创建在存储过程之外没有问题。
CREATE TABLE #objects
(
ObjectId INT
,SchemaName NVARCHAR(20)
,TableName NVARCHAR(50)
,ColumnName NVARCHAR(100)
,ObjectName NVARCHAR(150)
,Type NVARCHAR(50)
,ObjectDefinition NVARCHAR(MAX)
,IndexName NVARCHAR(100)
,IndexType NVARCHAR(50)
,IsPrimaryKey BIT
,IsUniqueKey BIT
);
INSERT INTO #objects (
ObjectId
,SchemaName
,TableName
,ColumnName
,ObjectName
,Type
,ObjectDefinition
,IndexName
,IndexType
,IsPrimaryKey
,IsUniqueKey
)
SELECT ObjectId = a.object_id
,SchemaName = SCHEMA_NAME ( a.schema_id )
,TableName = e.name
,ColumnName = COL_NAME ( b.parent_object_id, b.parent_column_id )
,ObjectName = OBJECT_NAME ( a.object_id )
,Type = a.type_desc
,ObjectDefinition = CAST(OBJECT_DEFINITION ( a.object_id ) AS NVARCHAR(MAX))
,IndexName = ch.name
,IndexType = ch.type_desc
,IsPrimaryKey = NULL
,IsUniqueKey = NULL
FROM sys.objects AS a
LEFT JOIN sys.default_constraints AS b
ON a.object_id = b.object_id
LEFT JOIN sys.check_constraints AS c
ON a.object_id = c.object_id
LEFT JOIN sys.tables AS e
ON e.object_id = a.parent_object_id
LEFT JOIN sys.indexes AS ch
ON a.object_id = ch.object_id
WHERE a.type_desc NOT IN ( 'INTERNAL_TABLE'
,'SYSTEM_TABLE'
,'SERVICE_QUEUE'
,'SQL_STORED_PROCEDURE'
,'SQL_INLINE_TABLE_VALUED_FUNCTION'
,'SQL_TABLE_VALUED_FUNCTION'
,'PRIMARY_KEY_CONSTRAINT'
,'UNIQUE_CONSTRAINT' )
AND ch.type_desc IN ( NULL
,'CLUSTERED COLUMNSTORE' )
UNION ALL
SELECT ObjectId = ix.object_id
,SchemaName = SCHEMA_NAME ( tab.schema_id )
,TableName = OBJECT_NAME ( tab.object_id )
,ColumnName = col.name
,ObjectName = ix.name
,Type = ix.type_desc
,ObjectDefinition = NULL
,IndexName = ix.name
,IndexType = ix.type_desc
,IsPrimaryKey = ix.is_primary_key
,IsUniqueKey = ix.is_unique_constraint
FROM sys.tables AS tab
INNER JOIN sys.indexes AS ix
ON tab.object_id = ix.object_id
INNER JOIN sys.index_columns AS ic
ON ic.object_id = ix.object_id
AND ic.index_id = ix.index_id
INNER JOIN sys.columns AS col
ON ix.object_id = col.object_id
AND col.column_id = ic.column_id
WHERE ix.is_primary_key = 1
OR ix.is_unique_constraint = 1
OR ix.type IN ( 1
,2 )
ORDER BY SchemaName
,Type;
我只需要解决错误,而存储过程中的其他事情我都没有问题。