How to create default constraint dependent other column in sql server

狂风中的少年 提交于 2019-12-01 19:02:46

问题


i have a table like this

tab1

create table tab1(ID int identity(1,1), Type varchar(10),IsValued bit)

tab1:

ID Type IsValued
----------------
1   S   1
2   R   0
3   R   0
4   S   1
5   S   1
6   R   0
7   S   1

instead of inserting value into IsValued column i want to create one constraint(NOT TRIGGER) when Type ='S' ,IsValued should be inserted as 1 and when Type ='R' ,IsValued should be inserted as 0

like : IsValued = case when Type ='S' then 1 when Type ='R' then 0 end

How can i achieve this..


回答1:


You want a computed column. For example:

CREATE TABLE tab1
(
 ID INT IDENTITY(1,1)
,[Type] VARCHAR(10)
,IsValued AS CASE [Type] WHEN 'S' THEN 1
                         WHEN 'R' THEN 0
             END
)

You can add to an existing table using the following syntax:

ALTER TABLE dbo.tab1 ADD IsValued AS CASE [Type] WHEN 'S' THEN 1
                                                 WHEN 'R' THEN 0
                                     END

You can make the column persisted by adding the keyword PERSISTED after the column creation. Persisting the column means that the field is stored on disk. When you insert or update a record, SQL server will work out the value at that point. If you don't, SQL Server will have to work it out each time you access the row. A good explanation can be found at SQL Server 2005 Computed Column Is Persisted

ALTER TABLE dbo.tab1 ADD IsValued AS CASE [Type] WHEN 'S' THEN 1
                                                 WHEN 'R' THEN 0
                                     END PERSISTED


来源:https://stackoverflow.com/questions/15521546/how-to-create-default-constraint-dependent-other-column-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!