INSERT存储过程中的用户默认列值

时间:2010-10-01 14:26:09

标签: asp.net sql stored-procedures insert default-value

从我的ASP.NET应用程序我调用INSERT存储过程,INSERT过程将数据放入表中的一列的默认值。如何指定我想要使用默认值? (或者我必须在参数中指定实际的默认值)

情况表:

Column 1: int
Column 2: string
Column 3: int default -1

情况存储程序

INSERT INTO TABLE
  (Column 1, Column 2, Column 3)
VALUES
  (?, ?, ?)

SITUATIONAL ASP.NET CODE

create paramter (Column 1, 12)
if (x = 0)
 {create parameter (Column 2, "test")}
else
 {
   create parameter (Column 3, 24)
   create parameter (Column 2, DBNull.Value)
 }

感谢您的帮助

4 个答案:

答案 0 :(得分:1)

将该列从insert子句中删除,您将获得默认值。

例如,在你的程序中:

IF condition
  INSERT INTO Y (X) VALUES(1); -- will use defaults
ELSE
  INSERT INTO Y (W, X) VALUES(1, 2) -- won't use default for W

答案 1 :(得分:1)

您可以使用default关键字。

CREATE TABLE #T
(
i int default 12,
j int
)

INSERT INTO #T (i,j)  VALUES (DEFAULT, 10)

SELECT i,j FROM #T
DROP TABLE #T

答案 2 :(得分:1)

if (somecondition) { // User another value for c2
   query = "insert into table_name (c1, c2) values (1, 2)";
} else { // User the column c2 default value
   query = "insert into table_name (c1) values (1)";
}

怎么样?

答案 3 :(得分:0)

在存储过程中,您可以将参数设置为自身具有默认值,这样,如果将该参数保留在应用程序代码之外,该过程将替换默认值。

@field_with_def_value int = -1,
etc...

如果需要,可以将该默认值设置为字段的默认值并使用它完成。但它可能更安全地测试sproc中的默认值,然后有条件地调用插入INSERT,无论该字段的值是否为该值。这样,如果更改了默认值,则无需更改应用程序或sproc代码