Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind a column default value to a function in SQL 2005

I have a column containing items that can be sorted by the user:

DOC_ID  DOC_Order DOC_Name
   1       1        aaa
   2       3        bbb
   3       2        ccc

I'm trying to figure out a way to properly initialize DOC_Order when the entry is created. A good value would either be the corresponding DO-CID (since it is autoassigned), or MAX(DOC-ORDER) + 1

After a bit of googling I saw it was possible to assign a scalar function's return to the default column.

CREATE FUNCTION [dbo].[NEWDOC_Order] 
(
)
RETURNS int
AS
BEGIN

RETURN (SELECT MAX(DOC_ORDER) + 1 FROM DOC_Documents)

END

But each of my tries using MS SQL Management studio ended in a "Error validating the default for column 'DOC_Order'" message.

Any idea of what the exact SQL syntax to assign a function to DEFAULT is?

like image 599
Luk Avatar asked Jan 14 '09 10:01

Luk


People also ask

What constraint assign a default value for a column?

The DEFAULT constraint is used to set a default value for a column. The default value will be added to all new records, if no other value is specified.

What is the default value of column in SQL?

Default values can be NULL, or they can be a value that matches the data type of the column (number, text, date, for example).


2 Answers

Here's screen shots to do it through SQL Server Management Studio GUI:

  1. Right click on table and select Design

enter image description here

  1. Select DOC_Order column (or other column needing default) in the table's design view to see properties

enter image description here

  1. Update Default Value or Binding with function name with brackets like so:

enter image description here

Note: as Luk stated, all brackets are needed including the schema (dbo in this case).

like image 72
Tony L. Avatar answered Nov 11 '22 20:11

Tony L.


The syntax to add a default like that would be

alter table DOC_Order 
add constraint 
df_DOC_Order 
default([dbo].[NEWDOC_Order]())
for DOC_Order

Also, you might want to alter your function to handle when DOC_Order is null

Create FUNCTION [dbo].[NEWDOC_Order] 
(
)
RETURNS int
AS
BEGIN

RETURN (SELECT ISNULL(MAX(DOC_ORDER),0) + 1 FROM DOC_Documents)

END
like image 38
cmsjr Avatar answered Nov 11 '22 20:11

cmsjr