如何知道默认值或存储值

时间:2016-08-09 06:57:38

标签: sql-server

我有一个表格字段,其默认值为' 0'用户可以为它存储任何数值。对于我的应用程序,我需要知道用户是否存储了任何值。

有没有办法找出查询中的列,用MSSQL返回它的默认值或存储值?

3 个答案:

答案 0 :(得分:2)

如上所述,您的问题的答案是从数据库返回现有行的查询将始终返回存储值

列的“默认值”仅在插入期间使用:

  1. 如果插入期间的列具有为其提供的值,请使用该值
  2. 如果插入期间的列没有为其提供的值,请使用默认值(如果指定了一个)
  3. 之后无法知道是否使用了0的默认值,或者插入是否为列提供了值0。

    因此查询将始终返回存储的值。

    推论:

    • 更改字段的默认值设置不会更改使用旧默认值插入的现有行。他们将保持现有价值。
    • 为允许null的字段添加默认值不会将其中包含null的现有行的此字段值设置为此新默认值,同样会保留其现有值( null)。

    您可以使用触发器和东西来检测没有提供任何值,然后使用“默认值”更新行,并在单独的列中设置复选标记或类似内容以指示“默认值为提供了“但SQL Server中没有内置的机制可以轻松地为您完成此任务。

答案 1 :(得分:0)

begin tran

insert into [dbo].[BuyOnlineCartMaster] (OfferAmt)values(0) 
        -- inserting value to some other column, 

select NetAmt from [BuyOnlineCartMaster] where CartID=SCOPE_IDENTITY()  
        -- default value is genereted in the required feild


rollback tran

select语句给出默认值

将此作为程序调用或其他内容

答案 2 :(得分:0)

您可以尝试以下

use tempdb

 create table #ttt 
(
        c1 int identity not null,
        c2 int not null,
        c3 int default -1,
        c4 as (case when c3 < 0 then c3+1 else c3 end),
        c5 as (case when c3 < 0 then 'DEFAULT VALUE' else 'USER SUPPLIED' end)
)


insert into #ttt values (10, 20)
insert into #ttt values (11, 21)
insert into #ttt (c2) values (20)

select * from #ttt

/*For selections, you can use */
Select C1, C2, C4 from #ttt