我的问题很简单,如何列出SQL Server 用户定义表类型的主键(列名)?
离;
CREATE TYPE [dbo].[MyTableType] AS TABLE
(
[ID] int NOT NULL, PRIMARY KEY CLUSTERED ( [ID])
)
如何使用查询
获取列[ID]
似乎只能找到真实表的主键,而不是表类型。
答案 0 :(得分:2)
这存储在目录视图中:
SELECT c.Name
FROM sys.table_types AS tt
INNER JOIN sys.key_constraints AS kc
ON kc.parent_object_id = tt.type_table_object_id
INNER JOIN sys.indexes AS i
ON i.object_id = kc.parent_object_id
AND i.index_id = kc.unique_index_id
INNER JOIN sys.index_columns AS ic
ON ic.object_id = kc.parent_object_id
INNER JOIN sys.columns AS c
ON c.object_id = ic.object_id
AND c.column_id = ic.column_id
WHERE tt.Name = 'YourTypeName';
答案 1 :(得分:1)
用户定义的表格不是实际的表格,因此它在sys.table_types
中有一个条目,而不在sys.tables
中。
如果使用sys.key_constraints
和sys.table_types.type_table_object_id
字段,则可以使用其他表格从sys.key_constraints.parent_object_id
检索关键信息,例如:
create TYPE TestTableType AS TABLE
(
ID int primary key,
Name nVARCHAR(50)
)
declare @typeID int
select @typeId=type_table_object_id
from sys.table_types
where name='TestTableType'
select @typeId
-- Returns 1134627085
select *
from sys.key_constraints
where parent_object_id=@typeID
-- Returns
-- PK__TT_TestT__3214EC27BA14A4A6 1150627142 NULL 4 1134627085 PK PRIMARY_KEY_CONSTRAINT 2016-04-25 17:36:34.890 2016-04-25 17:36:34.890 1 0 0 1 1
之后,您可以通过加入sys.index_columns
和sys.columns
来获得与其他主键相同的列名:
select col.name
from sys.key_constraints kcon
inner join sys.index_columns indcol on indcol.object_id=kcon.parent_object_id
inner join sys.columns col on col.object_id = kcon.parent_object_id
and col.column_id = indcol.column_id
where parent_object_id=@typeID
或者
select col.name
from sys.table_types tt
inner join sys.key_constraints kcon on type_table_object_id=kcon.parent_object_id
inner join sys.index_columns indcol on indcol.object_id=kcon.parent_object_id
inner join sys.columns col on col.object_id = kcon.parent_object_id and col.column_id = indcol.column_id
where tt.name='TestTableType'