달력

11

« 2024/11 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

Oracle 에서 사용했던 방법을 살짝 바꿨다.

나오는 결과에 비해서 쿼리가 길다. 어찌어찌하면 이쁘게 줄일 수도 있을 것 같은데... 너무 졸립다.
당연히 MSSQL 2005 이상부터 사용할 수 있을 듯..


WITH CTE (TNAME, CNAME, PRNUM, LEVEL) AS
(
SELECT convert(varchar(8000), TNAME) + '|', CNAME, PRNUM, 1 as LEVEL
FROM (
 SELECT object_name(object_id) TNAME
  , name CNAME
  , ROW_NUMBER () OVER (PARTITION BY name ORDER BY object_name(object_id)) PRNUM
 FROM sys.columns
 ) AA
WHERE PRNUM = 1
UNION ALL
SELECT CTE.TNAME + convert(varchar(8000), T.TNAME) + '|', T.CNAME, T.PRNUM, CTE.LEVEL + 1 LEVEL
FROM (
 SELECT object_name(object_id) TNAME
  , name CNAME
  , ROW_NUMBER () OVER (PARTITION BY name ORDER BY object_name(object_id)) PRNUM
 FROM sys.columns
 ) T INNER JOIN CTE ON CTE.PRNUM = (T.PRNUM - 1) AND T.CNAME = CTE.CNAME
WHERE T.PRNUM > 1
)
SELECT CTE.TNAME, CTE.CNAME, CTE.PRNUM
FROM CTE INNER JOIN (
SELECT CNAME, MAX(PRNUM) PRNUM
FROM (
 SELECT name CNAME
  , ROW_NUMBER () OVER (PARTITION BY name ORDER BY object_name(object_id)) PRNUM
 FROM sys.columns
 ) TA
GROUP BY CNAME) TABB ON CTE.CNAME = TABB.CNAME AND CTE.PRNUM = TABB.PRNUM;

Oracle의 SYS_CONNECT_BY_PATH  함수 같은거 쓸 수 있으면 좋을 거 같은데.. 찾아보기 너무 귀찮다.
:
Posted by Elick