--drop table tbl
create table tbl(id int, col1 int, col2 int, col3 int, col4 int, col5 int)
insert into tbl values(1, 1, 2, 3, 0, 0)
go
1. 간편한(?) 동적쿼리
declare @index int
set @index = 99
declare @sql varchar(1000)
declare @col varchar(10)
select @col = case when col1=0 then 'col1'
when col2=0 then 'col2'
when col3=0 then 'col3'
when col4=0 then 'col4'
when col5=0 then 'col5' end
from tbl where id=1
set @sql = 'update tbl set ' + @col + ' = ' + convert(varchar,@index) + 'where id=1'
exec (@sql)
select * from tbl
2. union 사용
declare @index int
set @index = 99
update tbl
set col1=case when min_sw='1' then @index else col1 end,
col2=case when min_sw='2' then @index else col2 end,
col3=case when min_sw='3' then @index else col3 end,
col4=case when min_sw='4' then @index else col4 end,
col5=case when min_sw='5' then @index else col5 end
from tbl t cross join
(
select min(sw) as min_sw
from (
select '1' as sw from tbl where id=1 and col1=0
union all
select '2' from tbl where id=1 and col2=0
union all
select '3' from tbl where id=1 and col3=0
union all
select '4' from tbl where id=1 and col4=0
union all
select '5' from tbl where id=1 and col5=0
) x
) y
where t.id=1
select * from tbl
방법2
--drop table tbl
create table tbl(id int, col1 int, col2 int, col3 int, col4 int, col5 int)
insert into tbl values(1, 0, 0, 1, 2, 1)
go
--테이블변수 사용
declare @t1 table(id int not null identity(1,1) primary key, val int)
declare @t2 table(id int not null identity(1,1) primary key, val int)
insert @t1
select case no when 1 then col1
when 2 then col2
when 3 then col3
when 4 then col4
when 5 then col5
end
from tbl cross join (select 1 as no
union all
select 2
union all
select 3
union all
select 4
union all
select 5) x
where tbl.id = 1
insert @t2
select val from @t1 where val > 0
select * from @t2
update tbl
set col1 = isnull((select val from @t2 where id=1),0),
col2 = isnull((select val from @t2 where id=2),0),
col3 = isnull((select val from @t2 where id=3),0),
col4 = isnull((select val from @t2 where id=4),0),
col5 = isnull((select val from @t2 where id=5),0)
where id=1
select * from tbl where id=1
출처 : sqler.pe.kr
'SQL' 카테고리의 다른 글
| 테이블 참조을 관계 구하는 쿼리 (0) | 2007/06/07 |
|---|---|
| DB 할당된 공간 알람을 띄우는 스크립트 (0) | 2007/06/07 |
| 특정컬럼이 0일때 select한후 업데이트 한방쿼리 (0) | 2007/06/07 |
| 현재 프로세스가 실행중인 쿼리 알아내기 (0) | 2007/06/07 |
| 분기별 합산 퀴리 (0) | 2007/06/07 |
| BOM전개 쿼리문 (0) | 2007/06/07 |




최근에 달린 댓글
링크
최근에 받은 트랙백
태그목록