How to create default constraint dependent other column in sql server

久未见 提交于 2019-12-01 19:22:52
twoleggedhorse

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