본문 바로가기
MS-SQL/Query

[MSSQL] TRIGGER AFTER UPDATE 업데이트 된 컬럼명 찾아보기

by Hwoarang757 2021. 2. 8.

COLUMNS_UPDATED() 를 이용하여 HEX 값을 이용하여 SYS.COLUMNS 테이블에서 컬럼명을 찾아내는 것 같습니다만 

계산되는 메카니즘을 전혀 이해 하지 못했습니다 -_-;;;

 

아래는 해당 내용 출처입니다..

 

출처 : stackoverflow.com/questions/8049810/how-to-get-updated-column-names-in-sql-server

 

How to get updated column names in sql server

I have a table called user with colums like FirstName,LastName,Age,Location,City,Education etc What I wanted to do is After a user Updates his information I wanted to track which are the columns...

stackoverflow.com

ALTER TRIGGER dbo.TRG_TEST
ON dbo.tbl_user 
	AFTER UPDATE 
AS
BEGIN 
DECLARE @TABLE_NAME VARCHAR(30)
SET @TABLE_NAME = 'TBL_USER'

DECLARE @TEST_TABLE TABLE
(
COLUMNNAME VARCHAR(20)
)

INSERT @TEST_TABLE
SELECT 'USER_ID'
UNION 
SELECT 'USER_NAME'


SELECT * FROM @TEST_TABLE WHERE COLUMNNAME IN
(
SELECT name FROM     sys.columns
						WHERE    object_id = OBJECT_ID (@TABLE_NAME)
									AND SUBSTRING(COLUMNS_UPDATED(),
									( ( column_id- 1 ) / 8 + 1 ),1) & ( POWER(2,( ( column_id- 1 ) % 8 + 1 )- 1) ) = POWER(2,( column_id - 1 )% 8)
)                                


END