ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์–ธ์–ด/DataBase

[SQL] UPDATE ๋ฌธ

NaNaRin๐Ÿ™ƒ 2021. 3. 11. 15:31

1. UPDATE ๋ฌธ

- ํŠน์ • ํ…Œ์ด๋ธ”์— ์ €์žฅ๋˜์–ด ์žˆ๋Š” ๋ฐ์ดํ„ฐ ๋‚ด์šฉ์„ ์ˆ˜์ •ํ•  ๋•Œ ์‚ฌ์šฉ

UPDATE [๋ณ€๊ฒฝํ•  ํ…Œ์ด๋ธ”]
SET	   [๋ณ€๊ฒฝํ•  ์นผ๋Ÿผ1]=[๋ฐ์ดํ„ฐ1], [๋ณ€๊ฒฝํ•  ์นผ๋Ÿผ2]=[๋ฐ์ดํ„ฐ2], … , [๋ณ€๊ฒฝํ•  ์นผ๋ŸผN]=[๋ฐ์ดํ„ฐN]
[WHERE ๋ฐ์ดํ„ฐ๋ฅผ ๋ณ€๊ฒฝํ•  ๋Œ€์ƒ ํ–‰์„ ์„ ๋ณ„ํ•˜๊ธฐ ์œ„ํ•œ ์กฐ๊ฑด]

-- 1. ๋ฐ์ดํ„ฐ ์ „์ฒด ์ˆ˜์ •ํ•˜๊ธฐ
UPDATE DEPT_TEMP
   SET LOC = 'SEOUL';

-- 2. ๋ฐ์ดํ„ฐ ์ผ๋ถ€๋ถ„๋งŒ ์ˆ˜์ •ํ•˜๊ธฐ
UPDATE DEPT_TEMP
   SET DNAME = 'DATABASE',
       LOC   = 'SEOUL'
 WHERE DEPTNO = 40;

  (1) DEPT_TEMP ํ…Œ์ด๋ธ”์˜ ๋ชจ๋“  ํ–‰์˜ LOC๊ฐ€ SEOUL๋กœ ๋ณ€๊ฒฝ๋œ๋‹ค

  (2) DEPT_TEMP ํ…Œ์ด๋ธ” ์ค‘ DEPTNO๊ฐ€ 40์ธ ํ–‰์˜ LOC๋งŒ SEOUL๋กœ ๋ณ€๊ฒฝ๋œ๋‹ค

 

2. ์„œ๋ธŒ์ฟผ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋ฐ์ดํ„ฐ ์ˆ˜์ •ํ•˜๊ธฐ

- INSERT ๋ฌธ๊ณผ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ UPDATE ๋ฌธ์—์„œ๋„ ์„œ๋ธŒ์ฟผ๋ฆฌ๋ฅผ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค

-- 1. ์—ฌ๋Ÿฌ ์นผ๋Ÿผ์„ ํ•œ๋ฒˆ์— ์ˆ˜์ •
UPDATE DEPT_TEMP
   SET (DNAME, LOC) = (SELECT DNAME, LOC
	  					 FROM DEPT
	 				    WHERE DEPTNO = 40)
 WHERE DEPTNO = 40;

-- 2. ์นผ๋Ÿผ ํ•˜๋‚˜ํ•˜๋‚˜ ์ˆ˜์ •
UPDATE DEPT_TEMP
   SET DNAME = (SELECT DNAME
	  			  FROM DEPT
	 			 WHERE DEPTNO = 40),
       LOC = (SELECT LOC
	  			FROM DEPT
	 		   WHERE DEPTNO = 40)
 WHERE DEPTNO = 40;

-- 3. UPDATE ๋ฌธ์˜ WHERE ์ ˆ์— ์„œ๋ธŒ์ฟผ๋ฆฌ ์‚ฌ์šฉ
UPDATE DEPT_TEMP
   SET LOC = 'SEOUL'
 WHERE DEPTNO = (SELECT DEPTNO
	  			   FROM DEPT_TEMP
	 			  WHERE DNAME = 'OPERATIONS');

  (1) DEPT_TEMP ํ…Œ์ด๋ธ”์˜ DNAME, LOC ์นผ๋Ÿผ์„ ํ•œ๋ฒˆ์— ์ˆ˜์ •

  (2) DEPT_TEMP ํ…Œ์ด๋ธ”์˜ DNAME, LOC ์นผ๋Ÿผ์„ ๊ฐ๊ฐ ๋ณ„๊ฐœ์˜ ์„œ๋ธŒ์ฟผ๋ฆฌ๋กœ ์ˆ˜์ •

  (3) UPDATE๋ฌธ ์•ˆ์˜ WHERE ์ ˆ์— ์„œ๋ธŒ์ฟผ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋ฐ์ดํ„ฐ๋ฅผ ์ˆ˜์ •

 

3. UPDATE ๋ฌธ ์‚ฌ์šฉ์‹œ ์œ ์˜์ 

- UPDATE ๋ฌธ๊ณผ DELETE ๋ฌธ์€ ํ…Œ์ด๋ธ”์— ์ด๋ฏธ ์กด์žฌํ•˜๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ์ˆ˜์ •ํ•˜๊ฑฐ๋‚˜ ์‚ญ์ œํ•˜๋Š” ๊ธฐ๋Šฅ์„ ์ˆ˜ํ–‰ํ•˜๋ฏ€๋กœ SELECT ๋ฌธ์ด๋‚˜ INSERT ๋ฌธ์— ๋น„ํ•ด ์œ„ํ—˜์„ฑ์ด ํฐ ๋ช…๋ น์–ด์ด๋‹ค. ๋”ฐ๋ผ์„œ UPDATE ๋ฌธ์„ ์ˆ˜ํ–‰ํ•˜๊ธฐ ์ „์— UPDATE๋ฌธ์˜ WHERE์ ˆ์„ ๊ฒ€์ฆํ•˜๋Š” ์ž‘์—…์ด ํ•„์š”ํ•˜๋‹ค