An IF inside a check constraint SQL

馋奶兔 提交于 2019-12-13 19:11:43

问题


I have this table..

CREATE TABLE [dbo].[Tipo_Servicios_Info](
[TSI_TS_Id] [int] NOT NULL,
[TS_Tar_Id] [int] NOT NULL,
[TS_PDI_Id] [int] NOT NULL,
[TSI_Descripcion] varchar(100),
[TSI_FechaIni] date not null,
[TSI_FechaFin] date not null,
[TSI_HoraMin] time,
[TSI_HoraMax] time,
[TSI_Duracion] varchar(50) not null,
[TSI_Unidad] varchar(50) not null,
[TSI_Cantidad] int not null,

CONSTRAINT [PK_TIPO_SERVICIOS_INFO] PRIMARY KEY CLUSTERED 
(
[TSI_TS_Id] ASC,
[TS_Tar_Id] ASC,
[TS_PDI_Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,
       ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

With some checks..

ALTER TABLE Dbo.Tipo_Servicios_Info
ADD CONSTRAINT Ck_Valores_Unidad CHECK(Tsi_Unidad IN('Dia', 'Hora'));
GO

ALTER TABLE Dbo.Tipo_Servicios_Info
ADD CONSTRAINT Df_Tipo_Servicios_Info_Tsi_Unidad DEFAULT 'Dia' FOR Tsi_Unidad;
GO

In this two above I set as default value of the TSI_Unidad to 'Dia', but this field only can contain Dia or Hora by the second constraint.

But i have a problem, I must define TSI_HoraMin and TSI_HoraMax that can be null(if TSI_Unidad is Dia, they have to be nullable), but if TSI_Unidad is Hora, [TSI_HoraMin] and [TSI_HoraMax] cant be null.

I want to create a new constraint but i dont know how can i do it..

This would be the idea..

ALTER TABLE [dbo].[Tipo_Servicios_Info]
ADD CONSTRAINT CK_HorasMin CHECK([TSI_HoraMin] is not null if [TSI_Unidad] = 'Hora')
GO

But this constraint, obviously, isnt well defined.


回答1:


From what I gather you are trying to not allow a null value for TSI_HoraMin if TSI_Unidad = 'Hora`. In which case you could use:

ALTER TABLE [dbo].[Tipo_Servicios_Info]
ADD CONSTRAINT CK_HorasMin 
CHECK(NOT([TSI_HoraMin] IS NULL AND [TSI_Unidad] = 'Hora'));


来源:https://stackoverflow.com/questions/12617743/an-if-inside-a-check-constraint-sql

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