2017-03-08 1 views
1

다른 열의 값에 따라 열을 업데이트하고 싶습니다. 이 같은 뭔가 :대소 문자를 사용하여 다른 열의 값에 따라 열을 업데이트하십시오.

update mt 
set 
case 
    when mt.type = 1 (1=float 2=boolean 3=datetime 4=character) 
    then mt.float_value = mt.value 
end 

case 
    when mt.type = 2 (1=float 2=boolean 3=datetime 4=character) 
    then mt.boolean_value = mt.value 
end 

case 
    when mt.type = 3 (1=float 2=boolean 3=datetime 4=character) 
    then mt.datetime_value = mt.value 
end 
... 
from myTable mt 

나는 열 mt.type

if the column mt.type = 1 then update mt.float_value with mt.value 
if the column mt.boolean_value = 2 then update mt.float_value with mt.value 

의 값에 따라 열 mt.float_value 또는 mt.boolean_value 또는 mt.datetime_value 또는 mt.char_value를 업데이트 할 등등 ... 가능하며이 업데이트를 어떻게 수행 할 수 있습니까? 도움을 감사

+0

테이블의 각 행에있는 많은 열 중 하나만 채울 때마다 스키마가 적절한 지 물어봐야합니다. 예를 들어, 값이 모든 데이터 유형이 될 수있는 키/값 쌍을 저장하려는 경우 모든 가능한 데이터 유형에 대한 열이있는 단일 테이블이 아닌 각 데이터 유형에 대해 별도의 테이블을 갖는 것이 좋습니다. 트리거는 주어진 키가 다양한 데이터 유형의 다중 값을 갖지 않도록하는 데 사용될 수 있습니다. 따로 : 당신의 질의에'where' 절이 부족하다는 것도 흥미 롭습니다. – HABO

답변

1

당신이 시도 할 수 있지만, 값 중 하나가 대상 열 유형으로 변환 할 수없는 경우는 실패합니다

세 가지 쿼리를 나눌 수
update mt 
set 
mt.float_value = case 
    when mt.type = 1 then convert(mt.value, float) else mt.float_value 
end, 

mt.boolean_value = case 
    when mt.type = 2 then convert(mt.value, bit) else mt.boolean_value 
end, 

mt.datetime_value = case 
    when mt.type = 3 then convert(mt.value, datetime) else mt.datetime_value 
end 
... 
from myTable mt 
+0

당신은 ['try_convert'] (https://msdn.microsoft.com/en-us/library/hh230993.aspx)로 변환 오류를 피할 수 있습니다. – Andomar

+0

감사합니다. 나는 이것을 시도 할 것입니다. –

2

:

update mt 
set  float_value = convert(value, float) 
where type = 1 

update mt 
set  bit_value = convert(value, bit) 
where type = 2 

update mt 
set  datetime_value = convert(value, datetime) 
where type = 3 
+0

당신의 솔루션은 꽤 좋은 것처럼 보입니다. 고맙습니다 –

관련 문제