DB

[MS-SQL] 쿼리(Query)에서 열 이름(column names)을 가져오는 방법

쿼리에서 열 이름(column names)을 가져오기

엑셀 다운로드를 위한 쿼리를 작성하였는데 엑셀 헤더값으로 들어갈 컬럼을 동적으로 가져와야하는 상황이 생겼다. 해결방법은 SYS 테이블을 이용하는 것이다.

SELECT name
FROM 
sys.dm_exec_describe_first_result_set
('작성한 쿼리문', NULL, 0) ;

가령 TB_USER 라는 테이블을 전체 조회했을 때 다음과 같이 작은 따옴표로 묶어서 스트링값으로 기입한다.

그렇게 하면 조회한 데이터들의 컬럼 값을 확인할 수 있다.

SELECT name
FROM 
sys.dm_exec_describe_first_result_set
('select * from TB_USER', NULL, 0) ;

만약, 프로시저에서 확인해야하는 경우라면 다음 예시와 같이 동적쿼리를 생성하면 유용하게 사용할 수 있다.

DECLARE @P_QUERY NVARCHAR(MAX) = '';
DECLARE @PIVOT   NVARCHAR(MAX) = '';

SET @PIVOT  = STUFF((SELECT '],['+ CODE_NAME FROM TB_COMMON_CODE WHERE COMPANY_ID = 'ORACLE' AND CODE_M = 'BIZ_TP'	 FOR XML PATH('')) + ']',1,1,'');
SET @PIVOT  = RIGHT(@PIVOT, LEN(@PIVOT) - 1);
 	

SET @P_QUERY ='
	SELECT * FROM (
		SELECT	SUBSTRING(calendar.YM, 3, 2 ) + ''년 '' + RIGHT(calendar.YM, 2) + ''월'' AS YM_NM
			,	calendar.BIZ_TYPE_NM
			,	ISNULL(exe_biz.EXE_BIZ_CNT, 0) AS ACT_CNT
		FROM  (
			SELECT	calendar.YM
				,	CODE_D AS BIZ_TYPE_CD
				,	code.CODE_NAME AS BIZ_TYPE_NM
				,	code.SORT_SEQ
			FROM (
				SELECT	CONVERT(VARCHAR(6), DATEADD(M, -number, CAST(''202208'' + ''01'' AS DATETIME)), 112) AS YM
				FROM MASTER..SPT_VALUES
				WHERE [TYPE] = ''P''
				AND number < 12
				) calendar
			LEFT JOIN TB_COMMON_CODE code ON (1=1)
			WHERE code.COMPANY_ID = ''ORACLE''
			AND code.CODE_M = ''ACT_TP''
		) calendar
		LEFT JOIN (
			SELECT	biz.ACT_DATE_YM AS YM
				,	biz.BIZ_TYPE_CD
				,	type_cd.CODE_NAME AS BIZ_TYPE_NM
				,	COUNT(*) AS EXE_BIZ_CNT
			FROM CRM_ACT act
			INNER JOIN TB_EMPLOYER emp ON (emp.COMPANY_ID = biz.COMPANY_ID AND emp.EMP_ID = biz.[USER_ID])
			INNER JOIN (
				SELECT	calendar.YM
					,	CODE_D AS BIZ_TYPE_CD
					,	code.CODE_NAME AS BIZ_TYPE_NM
					,	code.SORT_SEQ
				FROM (
					SELECT	CONVERT(VARCHAR(6), DATEADD(M, -number, CAST(''202208'' + ''01'' AS DATETIME)), 112) AS YM
					FROM MASTER..SPT_VALUES
					WHERE [TYPE] = ''P''
					AND number < 12					
				) calendar
				LEFT JOIN TB_COMMON_CODE code ON (1=1)
				WHERE code.COMPANY_ID = ''ORACLE''
				AND code.CODE_M = ''ACT_TP''			
			) calendar ON (calendar.YM = biz.ACT_DATE_YM AND calendar.BIZ_TYPE_CD = biz.BIZ_TYPE_CD)
			OUTER APPLY [dbo].[FN_COMMON_CODE](''ORACLE'', ''BIZ_TP'', biz.BIZ_TYPE_CD, ''Y'') type_cd
			WHERE biz.COMPANY_ID = ''ORACLE''
			AND biz.BIZ_USE_YN IN(''30'', ''40'')
			AND (22 = '''' OR emp.DEPT_ID = 22)
			AND biz.USE_YN = ''O''
			GROUP BY biz.COMPANY_ID, biz.ACT_DATE_YM, biz.BIZ_TYPE_CD, type_cd.CODE_NAME			
		)exe_biz ON (exe_biz.YM = calendar.YM AND exe_biz.BIZ_TYPE_CD = calendar.BIZ_TYPE_CD)
	) X
	PIVOT (
		MAX(ACT_CNT) FOR BIZ_TYPE_NM IN ([매수], [매도], [기타])
	) AS PIV
	ORDER BY YM_NM DESC '

SELECT 		@P_QUERY

EXECUTE(@P_QUERY)

SELECT name 
FROM 
sys.dm_exec_describe_first_result_set
(@P_QUERY, NULL, 0) ;

참고로, MASTER..SPT_VALUES 테이블을 이용하면 다음과 같은 ROW 데이터를 얻을 수 있으며 조인도 가능하다.

[MICROSOFT DOC]

sys.dm_exec_describe_first_result_set (Transact-SQL)Table of contents sys.dm_exec_describe_first_result_set (Transact-SQL) Article 05/16/2013 8 minutes to read In this article –> This dynamic management function takes a Transact-SQL statement as a parameter and describes the metadata of the first resultdocs.microsoft.com

[REFERENCE]

How to get column names from a query in SQL ServerUsing SQL Server. I have a very extensive query, with a lot of aliasing, etc… Is there a way, using just SQL (stored proc is fine, but not PHP, etc), to get a list of all column names from this…stackoverflow.com

Get Column Names of a Query in SQL ServerLet’s say I have a query in SQL 2014: SELECT EmployeeName, EmployeeAddress, EmployeeAge FROM dbo.Employee I would like to dynamically go through the query, loop and get the name of the columns likestackoverflow.com

Leave a Reply

error: Content is protected !!