Frage

I want to add a new column to an existing table.

I need it to emulate the enum type (in the way possible in SQL Server; with value constraints, that is).

The following doesn't work:

ALTER TABLE orders ADD [sent_to_panel] NVARCHAR(16) NULL;       
ALTER TABLE orders WITH CHECK ADD CONSTRAINT [CK_orders] CHECK (([sent_to_panel]='invalidated' OR [sent_to_panel]='not_sent' OR [sent_to_panel]='sent'));   
ALTER TABLE orders ADD CONSTRAINT [DF_orders_sent_to_panel]  DEFAULT (N'not_sent') FOR [sent_to_panel]; 
ALTER TABLE orders CHECK CONSTRAINT [CK_orders];    

I'm getting an error:

Msg 207, Level 16, State 1, Line 2
Invalid column name 'sent_to_panel'.

If I execute the first command on its own, though:

ALTER TABLE orders ADD [sent_to_panel] NVARCHAR(16) NULL;

The rest goes through.

So I suppose the problem is that the column isn't actually added yet (and thus not recognized by ADD CONSTRAINT) when trying to get it all done in one go.

The question is: how to make the script work properly?

War es hilfreich?

Lösung

CREATE TABLE a (
    b int
);

ALTER TABLE a
  ADD c nvarchar(16) NULL
    , CONSTRAINT check_this CHECK (c IN ('invalidated', 'not_sent', 'sent'))
    , CONSTRAINT defaultify DEFAULT ('not_sent') FOR c
;

ALTER TABLE a
  CHECK CONSTRAINT check_this
;

DROP TABLE a;
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top