问题描述
我有一列,其中包含可以由用户排序的项目:
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
我正在尝试计算在创建条目时提供了一种正确初始化DOC_Order的方法。一个好的值要么是相应的DO-CID(因为它是自动分配的),要么是MAX(DOC-ORDER)+ 1
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
但是我每次使用MS SQL Management Studio的尝试都以在验证 DOC_Order列的默认值时出错结尾。
But each of my tries using MS SQL Management studio ended in a "Error validating the default for column 'DOC_Order'" message.
是否知道将函数分配给DEFAULT的确切SQL语法是什么?
Any idea of what the exact SQL syntax to assign a function to DEFAULT is?
推荐答案
添加类似默认值的语法
alter table DOC_Order
add constraint
df_DOC_Order
default([dbo].[NEWDOC_Order]())
for DOC_Order
您可能想更改函数以在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
这篇关于将列默认值绑定到SQL 2005中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!