sql - Use default value of a column in stored procedures -


i using sql server 2012 , have 2 tables following definition

create table t1 (id int primary key, value nvarchar(10)) create table t2 (id int primary key, value bit default 1)  alter table t2 check add constraint fk foreign key(id) references t1 (id) 

i inserted following columns current example:

insert t1 values (1, 'a') insert t1 values (2, 'b') insert t1 values (3, 'c')  insert t2 values (1, 1) insert t2 values (3, 0) 

i running query , works

select   t1.*, isnull(t2.value, 1)   t1   left join t2 on t1.id = t2.id 

is there way replace 1 in part isnull(t2.value, 1) default value have defined in column value in table t2?

here sqlfiddle created example: sqlfiddle demo

update 1:
can't use sql server: find out default value of column query because returns ((1)) , can't cast ((1)) bit. there way fix that?

you not using default in manner intended. sql server evaluates internally @ time of insert (or potentially update if default keyword used).

it not intended use in select. consider can contain arbitrary expressions such default cast(getdate() int) % 2 or calling scalar udf. casting string bit won't evaluate expressions you.

the way evaluate separately

declare @b            bit         , @definition nvarchar(max)  select @definition = n'select @b = '                      + object_definition(default_object_id)   sys.columns  name = 'value'        , object_id = object_id('dbo.t2')  exec sys.sp_executesql   @definition,   n'@b bit output',   @b = @b output  select t1.*,        isnull(t2.value, @b)   t1        left join t2               on t1.id = t2.id  

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -