Question

I want to create a named default value in an ANSI compliant fashion, if possible, in a CREATE TABLE statement

If I try to add the CONSTRAINT as I would normally write it in an ALTER TABLE statement, it fails (at least in SQL SERVER, though I emphasise I am hoping to find an ANSI complaint statement as I would prefer it to work over a variety of Ado.NET DbConnections).

Example:

CREATE TABLE [dbo].[MyExample]
(
Id int NOT NULL IDENTITY (1, 1),
Name varchar(512) NOT NULL,         
IsActive bit NOT NULL,
CONSTRAINT PK_MyExample PRIMARY KEY CLUSTERED (Id),
CONSTRAINT DF_MyExample_IsActive  DEFAULT (1) FOR [IsActive]
)

Error:

Incorrect syntax near 'for'.

Was it helpful?

Solution

In terms of the SQL-92 Standard -- which is both ISO (I = International) and ANSI (A + American), by the way -- DEFAULT is not a constraint that may be given a name. In SQL-92 the DEFAULT can only be defined inline with the column definition and must be between the data type and the NOT NULL (if used) e.g.

CREATE TABLE T (c INTEGER DEFAULT 1 NOT NULL UNIQUE);

Note you have much non-Standard syntax in your small example:

  • square brackets as quoted identifiers (should be double quotes)
  • non-compliant data type (e.g. incorrect bit null behaviour)
  • abbreviated data types (e.g. int rather than INTEGER)
  • IDENTITY
  • CLUSTERED

OTHER TIPS

Is it not ANSI compliant?

CREATE TABLE [dbo].[MyExample]
(
    Id int NOT NULL IDENTITY (1, 1),
    Name varchar(512) NOT NULL,         
    IsActive bit NOT NULL CONSTRAINT DF_MyExample_IsActive DEFAULT (1),
    CONSTRAINT PK_MyExample PRIMARY KEY CLUSTERED (Id)
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top