header-img
Info :
728x90

CTE (Common Table Expression: ๊ณตํ†ต ํ…Œ์ด๋ธ” ์‹)

- ๊ธฐ์กด์˜ ๋ทฐ, ํŒŒ์ƒ ํ…Œ์ด๋ธ”, ์ž„์‹œ ํ…Œ์ด๋ธ” ๋“ฑ์œผ๋กœ ์‚ฌ์šฉ๋˜๋˜ ๊ฒƒ์„ ๋Œ€์‹  ํ•  ์ˆ˜ ์žˆ์œผ๋ฉฐ, ๋” ๊ฐ„๊ฒฐํ•œ ์‹์œผ๋กœ ๋ณด์—ฌ์ง€๋Š” ์žฅ์ ์„ ๊ฐ€์ง

- ์‹ค์ œ๋กœ CTE๋ผ๋Š” ํ‚ค์›Œ๋“œ๊ฐ€ ์ฝ”๋“œ ์•ˆ์— ๋“ค์–ด๊ฐ€์ง€๋Š” ์•Š๊ณ , WITH ๊ตฌ๋ฌธ์„ ์ด์šฉํ•จ.

- SELECT๋ฌธ์„ ๋ฏธ๋ฆฌ ์ •์˜ํ•˜์—ฌ ์ด๋ฆ„์„ ๋ถ™์ธ ํ›„, ์ด์–ด์ง€๋Š” ์ฟผ๋ฆฌ์—์„œ ํ…Œ์ด๋ธ”์ฒ˜๋Ÿผ ์‚ฌ์šฉํ•˜๋Š” ๊ธฐ๋Šฅ

- CTE๋Š” ๋ฐ”๋กœ ๋‹ค์Œ์— ์˜ค๋Š” select์ ˆ์—๋งŒ ํ•ด๋‹น CTE๋ฅผ ์ด์šฉํ•  ์ˆ˜ ์žˆ์Œ.

- ๋ชฉ์ ์— ๋”ฐ๋ผ ๋น„์žฌ๊ท€์  CTE, ์žฌ๊ท€ CTE๋กœ ๋‚˜๋ˆŒ ์ˆ˜ ์žˆ์Œ.

 

์žฌ๊ท€ CTE

- ์ตœ์ดˆ CTE๊ฐ€ ๋ฐ˜๋ณต์ ์œผ๋กœ ์‹คํ–‰๋˜์–ด ์ „์ฒด ๊ฒฐ๊ณผ ์ง‘ํ•ฉ์„ ์–ป์„ ๋•Œ๊นŒ์ง€ ๋ฐ์ดํ„ฐ์˜ ํ•˜์œ„ ์ง‘ํ•ฉ์„ ๋ฐ˜ํ™˜ํ•˜๋Š” CTE

- ๊ณ„์ธต์  ๋ฐ์ดํ„ฐ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ธฐ ์œ„ํ•œ ๋ชฉ์ ์œผ๋กœ ์‚ฌ์šฉ๋จ

- (**) ์žฌ๊ท€ CTE์—์„œ ๋ฌดํ•œ ๋ฃจํ”„๊ฐ€ ๋ฐœ์ƒํ•  ๊ฒฝ์šฐ๋ฅผ ๋Œ€๋น„ํ•˜์—ฌ, OPTION ์ ˆ์— MAXRECURSION ๊ฐ’์„ 0~32767 ์‚ฌ์ด์˜ ๊ฐ’์œผ๋กœ ์ง€์ •ํ•˜์—ฌ ์ตœ๋Œ€ ๋ฐ˜๋ณต ํšŸ์ˆ˜๋ฅผ ์ง€์ •ํ•  ์ˆ˜ ์žˆ์Œ. ๊ธฐ๋ณธ ๊ฐ’์€ 100์ด๋ฉฐ, 0์œผ๋กœ ์ง€์ •ํ•˜๋ฉด ์ตœ๋Œ€ ๋ฐ˜๋ณต ํšŸ์ˆ˜๊ฐ€ ์—†์–ด ๋ฌดํ•œ์œผ๋กœ ๋ฐ˜๋ณต๋จ.

 

ํ˜•์‹

WITH CTE_ํ…Œ์ด๋ธ”๋ช…(์—ด์ด๋ฆ„1, ์—ด์ด๋ฆ„2, ์—ด์ด๋ฆ„3 ...)
AS
(
    <์ฟผ๋ฆฌ๋ฌธ1 : SELECT * FROM TABLE_A>
    UNION ALL
    <์ฟผ๋ฆฌ๋ฌธ2 : SELECT * FROM TABLE_A JOIN CTE_ํ…Œ์ด๋ธ”๋ช…>
)
SELECT * FROM CTE_ํ…Œ์ด๋ธ”๋ช…;
728x90
๋”๋ณด๊ธฐ
BACKEND/MSSQL