Default column value based on the value of another column

SQL Server 2005. I have a table with the ColumnA bit, ColumnB int

Can I add a default value to ColumnB, so it ColumnBis 15 if it ColumnAis 1 and ColumnB0 if it ColumnAis 0?

I know that I could do this with a trigger, but I, my boss, was biased towards the triggers (he needs to train the sensitivity to fire).

+3
source share
6 answers

if your column B can only be 15 or zero, you can make it a computed column based on ColumnA. here is the code to add a new computed column:

ALTER TABLE YourTable ADD YourComputedColumn AS ColumnA*15
go
+8

- , , . - , . , /.

, - , ? , .

+1

? ... , , ?

+1

, , . , , , . , , ColumnB .

+1
+1

:

alter table yourTABLe add ColumnB as case when coalesce(ColumnA,0) = 15 then 0 else 1 end
go
0
source

Source: https://habr.com/ru/post/1732913/


All Articles