通常使用SQL Server,您可以像这样使用COLUMNPROPERTY
函数来查找数据库中的Identity列:
select TABLE_NAME + '.' + 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
但是我无法弄清楚如何在从另一个数据库运行查询时使其工作。例如。这不会返回任何结果:
Use FirstDatabase
Go
select TABLE_NAME + '.' + COLUMN_NAME, TABLE_NAME
from SecondDatabase.INFORMATION_SCHEMA.COLUMNS
where TABLE_SCHEMA = 'dbo'
and COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
order by TABLE_NAME
答案 0 :(得分:2)
Object_ID仅适用于当前数据库,除非您使用3部分名称,但该表单使用起来很复杂。此外,ColumnProperty仅适用于当前的数据库。
select o.name + '.' + c.name, o.name
from test1.sys.columns c
join test1.sys.objects o on c.object_id = o.object_id
join test1.sys.schemas s on s.schema_id = o.schema_id
where s.name = 'dbo'
and o.is_ms_shipped = 0 and o.type = 'U'
and c.is_identity = 1
order by o.name
答案 1 :(得分:2)
在其他数据库的COLUMNPROPERTY帮助下无法获取信息。但是有解决方法:
DECLARE @DatabaseName VARCHAR(MAX)
DECLARE @TableName VARCHAR(MAX)
DECLARE @SQL VARCHAR(MAX)
SET @DatabaseName = 'MyDatabase'
SET @TableName = 'MyTable'
SET @SQL = '
SELECT
C.TABLE_NAME,
C.COLUMN_NAME,
S.IS_IDENTITY
FROM ' + @DatabaseName + '.INFORMATION_SCHEMA.COLUMNS AS C
LEFT JOIN ' + @DatabaseName + '.SYS.COLUMNS AS S ON OBJECT_ID(''' + @DatabaseName + '.dbo.' + @TableName + ''') = S.OBJECT_ID AND C.COLUMN_NAME = S.NAME
WHERE S.IS_IDENTITY = 1'
EXEC(@SQL)
答案 2 :(得分:1)
这对我来说使用了一个特定的数据库:
USE <database_name>;
GO
SELECT SCHEMA_NAME(schema_id) AS schema_name
, t.name AS table_name
, c.name AS column_name
FROM sys.tables AS t
JOIN sys.identity_columns c ON t.object_id = c.object_id
ORDER BY schema_name, table_name;
GO
答案 3 :(得分:0)
在这个例子中,我在“Database1”中构建了一个存储过程,它使用动态SQL从“Database2”中的表中检索列信息(使用驻留在“Database2”中的[INFORMATION_SCHEMA]。[COLUMNS]系统视图) ):
ALTER PROCEDURE [Database1].[Schema1].[ColumnNames] @Database2 nvarchar(128), @Schema2 nvarchar(128), @Table2 nvarchar(128)
AS
BEGIN
DECLARE @Sql nvarchar(1000)
SET @Sql = 'SELECT [COLUMN_NAME], [ORDINAL_POSITION] FROM [' + @Database2 + '].[INFORMATION_SCHEMA].[COLUMNS]
WHERE [TABLE_SCHEMA] = ''' + @Schema2 + ''' AND [TABLE_NAME] = ''' + @Table2 + ''''
EXEC(@Sql)
END
答案 4 :(得分:0)
我正在使用SQL Server 2019,并且遇到了同样的挑战。我不确定此修复程序是否适用于旧版本,但是每个数据库中都有一个名为 Your-DB-Name.sys.identity_columns 的视图。如果从该视图中选择,您将看到在该数据库中定义的标识列的列表。
根据这些信息,您应该能够编写一个连接 YourDBName.Information_schema.columns 的联接,如下所示:
选择*
从YourDBName.Information_Schema.columns col
左外连接YourDBName.sys.identity_columns idc
开启idc.name = col.COLUMN_NAME和idc.object_id = object_id('YourDBName..YourTableName')
其中col.TABLE_NAME ='YourTableName'和col.table_catalog ='YourDBName';
YourDbName.sys.identity_columns 视图包含以下可能有用的字段: