在SQL Server中是否已记录$ IDENTITY并且可靠?


8

我了解到SQL Server可以使用伪列返回表的(单个)标识列的值$IDENTITY

SELECT $IDENTITY FROM Table

此功能是否已记录且可靠?唯一官方提及的内容是在IDENTITY页面上,但它已包含在代码示例中。这表明它可能打算不做记录。与此功能相匹配的Google也很少。

Answers:


12

$IDENTITY(和$ROWGUID)记录在SELECT子句(Transact-SQL)中

我会警告不要使用它,因为当表没有标识列时,它将引发错误。举两个例子-第一个可行(检查“结果”选项卡),但是第二个抛出错误:

CREATE TABLE #EmployeesWithIdentity (EmployeeID INT IDENTITY(1,1), EmployeeName VARCHAR(50));
SELECT $IDENTITY FROM #EmployeesWithIdentity;
GO

CREATE TABLE #Employees (EmployeeName VARCHAR(50));
SELECT $IDENTITY FROM #Employees;
GO

这是第二个产生的东西:

Msg 207, Level 16, State 1, Line 6
Invalid column name '$IDENTITY'.

如果您要查找哪些列具有标识字段,那么我将使用此Stack Overflow帖子中描述的方法:

select COLUMN_NAME, TABLE_NAME
from INFORMATION_SCHEMA.COLUMNS
where TABLE_SCHEMA = 'dbo'
and COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
order by TABLE_NAME

或者,使用目录视图:

SELECT s.name,t.name,c.name
FROM sys.schemas AS s 
JOIN sys.tables AS t ON s.[schema_id] = t.[schema_id]
JOIN sys.identity_columns AS c ON t.[object_id] = c.[object_id];
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.