Hi,
Running SQL Server 2008 R2. DDL below:
CREATE TABLE [dbo].[Test]
(
[TestID] [bigint] NOT NULL IDENTITY,
[Column1] [varchar](50) NOT NULL,
[Column2] [varchar](50) NULL,
[Column3] [varchar](50) NULL,
[Flag] [bit] NOT NULL,
CONSTRAINT [PK_Test_TestID] PRIMARY KEY CLUSTERED ([TestID] ASC)
)
GO
ALTER TABLE [dbo].[Test] ADD CONSTRAINT [DF_Test_Flag] DEFAULT ((0)) FOR [Flag]
GO
How would I go about adding a constraint that satisfies the following conditions:
- If Flag is set to 0 (or null for new rows that have yet to have the default constraint applied), then require non-empty values in Column2 and Column3,
- If Flag is set to 1, then require null values in Column2 and Column3
I tried the constraint below but it's not working (preventing insert of row):
ALTER TABLE [dbo].[Test] WITH CHECK ADD CONSTRAINT [CN_Test_Flag] CHECK (ISNULL([Flag], 0) = 0 AND [Column2] IS NOT NULL AND [Column3] IS NOT NULL)
GO
Any thoughts?
Thanks!