我通常使用以下sql找到sql server中表的所有列名
SELECT Upper(column_name) FROM information_schema.columns
WHERE table_name ='MUTABLE'
但是,现在我想找到同义词的所有列名。有什么方法可以做到这一点?
恕我直言你不应该使用
INFORMATION_SCHEMA
来实现这些。以下内容适用于表或视图:
SELECT UPPER(name)
FROM sys.columns
WHERE OBJECT_NAME([object_id]) = N'mutable';
以下内容适用于同义词(您稍后更改的要求):
SELECT UPPER(name)
FROM sys.columns AS c
CROSS APPLY
(
SELECT name
FROM sys.synonyms
WHERE name = N'mutable'
AND OBJECT_ID([base_object_name]) = c.[object_id]
) AS x;
你也可以直接说:
DECLARE @obj INT;
SELECT @obj = OBJECT_ID([base_object_name])
FROM sys.synonyms WHERE name = N'mutable';
SELECT UPPER(name) FROM sys.columns WHERE [object_id] = @obj;
sys.synonyms
来发现base_object_name
,然后从那里使用sys.columns
,如@Aaron所示:
select * from sys.columns where
object_id = OBJECT_ID((select base_object_name from sys.synonyms
where name='mutable'))
尝试将同义词中的前零行选择到临时表中。这将创建一个与基础对象具有相同列名的表。然后在tempdb中查询sys.columns:
SELECT TOP(0) * INTO #tmpColumns FROM mutable;
SELECT name FROM tempdb.sys.columns WHERE object_id = OBJECT_ID('tempdb.dbo.#tmpColumns');