从join语句中获取字段名称(展开* star)

时间:2013-01-30 05:00:46

标签: tsql ssms

我最近在ad-hoc查询中构建了相当冗长的连接,我发现在我加入工作后输入select语句中的所有字段名称非常繁琐。有没有一种快速方法可以在组合查询中列出所有字段名称?是否有一些查询针对select语句或key命令运行?

例如,下面的联接中可能有大约30个字段。如果我可以快速列出他们从'*'明星扩展它们,那么我就可以拿走我不需要的东西。

SELECT *
FROM [DB].[THINGS].[QLINKS] Q
JOIN [DB].[THINGS].[POINTS] RQ
    ON Q.ID = RQ.POINT_ID
JOIN [DB].[THINGS].[REFERENCES] R
    ON RQ.POINT_ID = R.ID
JOIN SA_MEMBERSHIP.DBO.ASPNET_USERS U
    ON U.USERID = R.PERSON_ID
JOIN SA_MEMBERSHIP.DBO.ASPNET_MEMBERSHIP M
    ON M.USERID = U.USERID
WHERE NOT Q.ID IN (
        SELECT RQ.QLINK_ID
        FROM [DB].[DATA].[ENTRIES] E
        JOIN [DB].[THINGS].[REFERENCES] R
            ON E.PERSON_ID = R.PERSON_ID
        JOIN [DB].[THINGS].[POINTS] RQ
            ON R.ID = RQ.POINT_ID
        WHERE (
                ITEMKEY LIKE '102_0%'
                OR ITEMKEY LIKE '104_0%'
                )
            AND E.POINT_ID IS NULL
        GROUP BY E.PERSON_ID, LEFT(ITEMKEY, 5), R.ID, RQ.QLINK_ID
        )

2 个答案:

答案 0 :(得分:2)

类似以下内容(tsql版本,想法是使用结果集的元数据),光标c是您的查询

declare c cursor for select * from sys.databases
go
open c


DECLARE @Report CURSOR;
declare @cn sysname
declare @op int
declare @ccf int
declare @cs int
declare @dts smallint
declare @cp tinyint
declare @colsc tinyint
declare @orp int
declare @od varchar(1)
declare @hc smallint
declare @cid int
declare @oid int
declare @dbid int
declare @dbn sysname

exec sp_describe_cursor_columns @cursor_return = @Report out, @cursor_source = N'global', @cursor_identity = N'c';

declare @res nvarchar(max)
set @res = '';

FETCH NEXT from @Report into @cn, @op, @ccf, @cs, @dts, @cp, @colsc, @orp, @od, @hc, @cid, @oid, @dbid, @dbn;
WHILE (@@FETCH_STATUS <> -1)
BEGIN
    set @res = @res +',' + @cn
   FETCH NEXT from @Report into @cn, @op, @ccf, @cs, @dts, @cp, @colsc, @orp, @od, @hc, @cid, @oid, @dbid, @dbn;
END

print stuff(@res, 1, 1, '')

CLOSE @Report;
DEALLOCATE @Report;
GO

close c
deallocate c

答案 1 :(得分:0)

事实证明,有一个插件!插件ApexSQL重构免费提供此功能。

此处有直接链接:http://www.apexsql.com/sql_tools_refactor.aspx

尊敬的Pinal Dave在此描述:http://blog.sqlauthority.com/2014/07/24/sql-server-how-to-format-and-refactor-your-sql-code-directly-in-ssms-and-visual-studio/