July 15, 2009 at 9:05 am
OK i'm feeling extra dumb today... I want to to run a CREATE TABLE statement which features a named default constraint. an inline definition, which generates a name automatically is no problem.
I can't seem to do it in a single statement/operation...only with a seperate ALTER TABLE ADD CONSTRAINT.
what am i doing wrong?
here's the working example:
CREATE TABLE [dbo].[MYEXAMPLE] (
[EXAMPLEID] INT IDENTITY(1,1) NOT NULL,
[EXAMPLEFLAG] CHAR(1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
--[EXAMPLEFLAG] CHAR(1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL DEFAULT 'N', --works if included, no problem..but it's not named!
CONSTRAINT [PK__MYEXAMPLE__EXAMPLEID] PRIMARY KEY CLUSTERED (EXAMPLEID),
CONSTRAINT [CK__MYEXAMPLE__EXAMPLEFLAG] CHECK ([EXAMPLEFLAG]='N' OR [EXAMPLEFLAG]='Y') )
ALTER TABLE [MYEXAMPLE] ADD CONSTRAINT [DF__MYEXAMPLE__EXAMPLEFLAG] DEFAULT ('N') FOR EXAMPLEFLAG WITH VALUES
and here's what I'm trying to do, but it fails:
DROP TABLE MYEXAMPLE
CREATE TABLE [dbo].[MYEXAMPLE] (
[EXAMPLEID] INT IDENTITY(1,1) NOT NULL,
[EXAMPLEFLAG] CHAR(1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
CONSTRAINT [PK__MYEXAMPLE__EXAMPLEID] PRIMARY KEY CLUSTERED (EXAMPLEID),
CONSTRAINT [CK__MYEXAMPLE__EXAMPLEFLAG] CHECK ([EXAMPLEFLAG]='N' OR [EXAMPLEFLAG]='Y'),
CONSTRAINT [DF__MYEXAMPLE__EXAMPLEFLAG] DEFAULT ('N') FOR (EXAMPLEFLAG) )
Lowell
July 15, 2009 at 9:10 am
DROP TABLE MYEXAMPLE
go
CREATE TABLE [dbo].[MYEXAMPLE] (
[EXAMPLEID] INT IDENTITY(1,1) NOT NULL,
[EXAMPLEFLAG] CHAR(1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
CONSTRAINT [DF__MYEXAMPLE__EXAMPLEFLAG] DEFAULT ('N'),
CONSTRAINT [PK__MYEXAMPLE__EXAMPLEID] PRIMARY KEY CLUSTERED (EXAMPLEID),
CONSTRAINT [CK__MYEXAMPLE__EXAMPLEFLAG] CHECK ([EXAMPLEFLAG]='N' OR [EXAMPLEFLAG]='Y')
)
Why not make the EXAMPLEFLAG column NOT NULL if you are going to have a default on it?
July 15, 2009 at 9:14 am
it was just an example so i could get the named default constraint in there somewhere ...i didn't really think it through;
Lowell
July 15, 2009 at 9:45 am
This should work for you.
DROP TABLE MYEXAMPLE
CREATE TABLE [dbo].[MYEXAMPLE] (
[EXAMPLEID] INT IDENTITY(1,1) NOT NULL,
[EXAMPLEFLAG] CHAR(1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL CONSTRAINT [DF__MYEXAMPLE__EXAMPLEFLAG] DEFAULT ('N'),
CONSTRAINT [PK__MYEXAMPLE__EXAMPLEID] PRIMARY KEY CLUSTERED (EXAMPLEID),
CONSTRAINT [CK__MYEXAMPLE__EXAMPLEFLAG] CHECK ([EXAMPLEFLAG]='N' OR [EXAMPLEFLAG]='Y'))
July 15, 2009 at 10:02 am
Thanks Michael and Robert;
I was stuck thinking I could append the default at the end, like i've done with PK/UQ/FK and check constraints.... instead of still part of the column definition.
Lowell
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply