如何使用默认约束? [英] How to Use Default Constraint?

查看:118
本文介绍了如何使用默认约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手。我正在尝试学习默认约束。



我创建了一个表格如下。



I''m a newbie. I''m trying to learn default constraints.

I have created a table as below.

CREATE TABLE PERSONS1
(
Emp_ID int CONSTRAINT Constpk PRIMARY KEY,
Emp_Name varchar(40),
Emp_City varchar(20) DEFAULT 'Bangalore'
)







但是,我无法使用以下代码插入值。






However, I''m unable to insert the values using the following codes.

INSERT INTO PERSONS1
VALUES ( 21, 'John',NULL)





空值在City栏中更新







NULL Value is updated in City column
OR

INSERT INTO PERSONS1
VALUES ( 212, 'John','')



City列中没有值








No values in City column

OR

INSERT INTO PERSONS1
VALUES ( 213, 'John')





我收到错误信息。





我哪里错了?请帮帮我!



我是使用sql server r2 2008



提前谢谢!



I get an error message for this.


Where am I going wrong? Please help me out!

I''m using sql server r2 2008

Thanks in advance!

推荐答案

第三个几乎是正确的,但是因为如果省略一个字段,你必须指定你传递的是哪个。 br />
The third is almost the right one, but since if you omit a field, you have to specify which are you passing.
INSERT INTO PERSONS1(Emp_ID, Emp_Name) VALUES ( 213, 'John')


试试



try

INSERT INTO PERSONS1 (Emp_ID,Emp_Name)
VALUES ( 21, 'John');





默认约束将在你发挥作用时发挥作用o不通过insert语句输入任何值。



另外,希望列Emp_Id不是自动编号列



Default constraint will come into play when you do not input any value via insert statement.

Also, hope the column Emp_Id is not an auto number column


原因您的前两个查询未能使用默认值是因为您在那里明确设置了一个值。默认值不用于替换空值或空字符串 - 当您不提供时,它会放入一个值(这与显式选择空值不同)。



第三个例子中的失败是因为 INSERT 需要三个值而你只提供两个。在这种情况下,您必须设置您希望插入自己的列,例如
The reason your first two queries fail to use the default value is because you explicitly set a value there. A default value is not used to replace a null value or empty string - it is there to put in a value when you don''t supply one (this is not the same as explicitly choosing a null value).

The failure in your third example is because the INSERT expects three values and you only supply two. In cases like this, you have to set the columns you are expecting to insert into yourself like this
insert into persons1(emp_id, emp_name)
values (213, 'John')

现在,当您运行该查询时,数据库引擎看到你没有为Emp_City提供一个值,所以它将应用班加罗尔的默认值。

Now, when you run that query, the database engine sees that you haven''t supplied a value for Emp_City, so it will apply the default value of Bangalore.


这篇关于如何使用默认约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆