Define Data Type of Computed Column

北慕城南 提交于 2020-01-25 11:09:14

问题


I have a computed column specified as follows:

(case when [StartDate]<=getdate() AND [EndDate] IS NULL then (1) else (0) end)

I'm trying to use the value of this column in Entity Framework. Is there any possible way to have this recognized as a boolean? That, or can I have it defined as a bit in my database, based on its return values? As it is, Entity Framework considers it an int (as it seems to do whenever it's not clear).


回答1:


Simply cast the value to bit, like this:

CAST ((case when [StartDate]<=getdate() AND [EndDate] IS NULL 
       then (1) else (0) end) AS BIT)

EF will automatically recognize this column as boolean.

In fact the original query returns an integer, and that's why EF recognizes it as integer. In SQL Server, unless you say the contrary, 1 and 0 are integer values. You must use CAST (0 as BIT) or CAST (1 as BIT) if you want SQL Server to recognize them as boolean (bit) type.




回答2:


try this:

drop table ##test;
create table ##test (
  [id] [bigint]
  , [computed] as cast([id] as [float]) * .99
  );
insert into ##test
            ([id])
values     (9999999999);
select *
from   ##test; 

来源:https://stackoverflow.com/questions/25493051/define-data-type-of-computed-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!