MS-Sql에서 Select문을 이용한 Update 쿼리
Table_name_2 부분에 Select문을 넣어줌
SET Table_name_1.column_name_1
= Table_name_2.column_name_1
FROM Table_name_1,
Table_name_2
WHERE Table_name_1.column_name_pk
= Table_name_2.column_name_pk
- 다른테이블의 값을 쓰는 경우 -
drop table TS_QUERY_TEST;
drop table TS_QUERY_TEST_2;
create table TS_QUERY_TEST
(
ID varchar(10) primary key,
content varchar(20)
);
create table TS_QUERY_TEST_2
(
ID varchar(10) primary key,
content varchar(20)
);
insert into TS_QUERY_TEST (id,content) values ( '1','11111');
insert into TS_QUERY_TEST (id,content) values ( '2','22222');
insert into TS_QUERY_TEST (id,content) values ( '3','33333');
insert into TS_QUERY_TEST (id,content) values ( '4','44444');
insert into TS_QUERY_TEST (id,content) values ( '5','55555');
insert into TS_QUERY_TEST_2 (id,content) values ( '1','111');
insert into TS_QUERY_TEST_2 (id,content) values ( '2','222');
insert into TS_QUERY_TEST_2 (id,content) values ( '3','333');
insert into TS_QUERY_TEST_2 (id,content) values ( '4','444');
insert into TS_QUERY_TEST_2 (id,content) values ( '5','555');
/* before */
select * from TS_QUERY_TEST;
select * from TS_QUERY_TEST_2;
update TS_QUERY_TEST
set content = (
select content from TS_QUERY_TEST_2
where TS_QUERY_TEST.ID = ID
)
/* after */
select * from TS_QUERY_TEST;
select * from TS_QUERY_TEST_2;
-동일 테이블의 값을 쓰는 경우
use shims
drop table TS_QUERY_TEST;
create table TS_QUERY_TEST
(
ID varchar(10) primary key,
content varchar(20),
pid varchar(10)
);
insert into TS_QUERY_TEST (id,content,pid) values ( '1','11111','');
insert into TS_QUERY_TEST (id,content,pid) values ( '2','22222','1');
insert into TS_QUERY_TEST (id,content,pid) values ( '3','33333','2');
insert into TS_QUERY_TEST (id,content,pid) values ( '4','44444','3');
insert into TS_QUERY_TEST (id,content,pid) values ( '5','55555','4');
/* before */
select * from TS_QUERY_TEST;
update TS_QUERY_TEST
set content = B.content
from TS_QUERY_TEST
, TS_QUERY_TEST as B
where TS_QUERY_TEST.pid = B.ID;
/* after */
select * from TS_QUERY_TEST;
'프로그램&DB > MS-SQL' 카테고리의 다른 글
MS-SQL UPDATE 문에서 Case When 사용하여 전체 업데이트 (0) | 2013.08.27 |
---|---|
[MS-Sql] Select문을 이용한 Update 쿼리 (0) | 2012.12.11 |
MSSQL 테이블 복사 (0) | 2012.07.05 |
MS-Sql 테이블 및 저장프로시저 목록 가져오기 (0) | 2012.04.10 |
Mass SQL 인젝션으로 삽입된 악성코드 일괄 삭제 (0) | 2009.04.15 |