我正在尝试获取具有特定类型的列的名称(因此我可以动态查询结果)。下面的代码似乎让我接近(因为类型= 56代表int)但它似乎是不正确的。更不用说我没能找到从类型到int表示的良好映射。
SELECT c.system_type_id as type
FROM SYS.COLUMNS c
JOIN SYS.TABLES t ON c.object_id = t.object_id
WHERE t.name = 'MyTableName'
由于
答案 0 :(得分:1)
您可以在sys.types
目录视图中找到类型的映射:
SELECT c.name as column_name, ty.name as type_name
FROM SYS.COLUMNS c
JOIN SYS.TABLES t ON c.object_id = t.object_id
JOIN SYS.TYPES ty ON c.system_type_id = ty.system_type_id
WHERE t.name = 'MyTableName'
答案 1 :(得分:0)
SELECT
c.name 'Column Name',
t.Name 'Data type'
FROM
sys.columns c INNER JOIN
sys.types t ON c.user_type_id = t.user_type_id
LEFT OUTER JOIN sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
LEFT OUTER JOIN sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
WHERE
c.object_id = OBJECT_ID('TableName')
答案 2 :(得分:0)
假设您正在使用SQL Server,您可以执行以下操作;
DECLARE @DataType varchar(20); SET @DataType = 'int'
SELECT
o.name TableName
,c.name ColumnName
,t.name ColumnType
,t.max_length ColumnLength
FROM sys.columns c
JOIN sys.objects o
ON c.object_id = o.object_id
JOIN sys.types t
ON c.user_type_id = t.user_type_id
WHERE t.name LIKE '%' + @DataType + '%'
AND o.type_desc = 'USER_TABLE'
只需更改变量中的数据类型,它就会显示如下列表
TableName ColumnName ColumnType ColumnLength
Employees empid int 4
Employees mgrid int 4
Suppliers supplierid int 4
Categories categoryid int 4
Products productid int 4
Products supplierid int 4
您可以修改此项以添加表格名称,如果这是您想要做的事情。