Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Trigger? Constraint? Computed column?

Author  Topic 

Zcumbag
Starting Member

3 Posts

Posted - 2007-02-23 : 17:52:49
Hi.

I was wondering how I should go about doing this thing. I need to put a value in a column that is based on values on other columns in the same row.

insert into myTable(Col1, Col2)
values(25, -14)

When this statement executes I need to put a value in Col3. Like:

if(Col1 >0 AND Col2 <0)
set Col3 = Col1 - Col2
else
set Col3 = Col1;

I don't now quite how to solve this. I am really going to need this value in a column. Calculating the value at retrieval is not on option...

I appreciate all help.

Thanks!


khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2007-02-23 : 20:38:11
[code]
declare @col1 int,
@col2 int

select @col1 = 25,
@col2 = -14

insert into myTable (Col1, Col2, Col3)
select @col1, @col2,
case when @col1 > 0 and @col2 < 0 then @col1 - @col2
else @col1
end
[/code]


KH

Go to Top of Page

mahesh_bote
Constraint Violating Yak Guru

298 Posts

Posted - 2007-02-27 : 05:52:30
quote:
Originally posted by khtan


declare @col1 int,
@col2 int

select @col1 = 25,
@col2 = -14

insert into myTable (Col1, Col2, Col3)
select @col1, @col2,
case when @col1 > 0 and @col2 < 0 then @col1 - @col2
else @col1
end



KH





khtan, i think he wants to update into the table. hopes this will work

update test set col3 = case when col1 > 0 and col2 < 0 then col1 - col2 else col1 end
where col1 = <value>

thanks,

Mahesh
Go to Top of Page

harsh_athalye
Master Smack Fu Yak Hacker

5581 Posts

Posted - 2007-02-27 : 06:06:55
quote:
Originally posted by mahesh_bote

quote:
Originally posted by khtan


declare @col1 int,
@col2 int

select @col1 = 25,
@col2 = -14

insert into myTable (Col1, Col2, Col3)
select @col1, @col2,
case when @col1 > 0 and @col2 < 0 then @col1 - @col2
else @col1
end



KH





khtan, i think he wants to update into the table. hopes this will work

update test set col3 = case when col1 > 0 and col2 < 0 then col1 - col2 else col1 end
where col1 = <value>

thanks,

Mahesh



Why UPDATE? When you can do it while inserting itself !

Harsh Athalye
India.
"The IMPOSSIBLE is often UNTRIED"
Go to Top of Page
   

- Advertisement -