简体   繁体   English

SQL Server中的Isnull和数据类型

[英]Isnull and data type in SQL Server

Suppose I have a table like: 假设我有一个像这样的表:

Tab(MyDate datetime null, MyIs bit null, ...)

Then I have SQL Like 然后我有SQL喜欢

    select Isnull(MyDate, 1), IsNull(MyIs, 999) from Tab;

If MyDate , MyIs value is null in DB, the result is: 如果MyDateMyIs值在DB中为null ,则结果为:

    MyDate                   MyIs  
    1900-01-02 00:00:00.000  1

Not the expected value like 不是预期的价值

MyDate        MyIs  
1             999

So it looks like the return value is based on data type of the column. 因此看起来返回值基于列的数据类型。 How to resolve this issue? 如何解决这个问题?

For my testing case as above, I Only got one row from the table. 对于我上面的测试用例,我只从表中得到一行。

The way you're looking for, you don't. 你正在寻找的方式,你没有。

All the values in the same column must be the same data type. 同一列中的所有值必须是相同的数据类型。 If your data had NOT NULL values in some rows (returning the column's data-type) and NULL values in other rows (returning a different data type, as per your CASE statement) , you would break this requirement. 如果您的数据在某些行中具有NOT NULL值(返回列的数据类型),而在其他行中返回 NULL值(根据CASE语句返回不同的数据类型) ,则会破坏此要求。

You could have two extra fields... 你可以有两个额外的字段......

select
  MyDate,
  CASE WHEN MyDate IS NULL THEN 1   ELSE 0 END As MyDateWibble,
  MyIs,
  CASE WHEN MyIs   IS NULL THEN 999 ELSE 0 END AS MyIsWibble
FROM
  Tab;

You could CAST() everything to VARCHAR() and return strings instead of DATETIME , BIT or INT . 您可以将所有内容CAST()VARCHAR()并返回字符串而不是DATETIMEBITINT

But, more probably, I'd review the reason you want to do this in the first place and work out an alternative design. 但是,更有可能的是,我会首先回顾你想要做到这一点的原因,并制定一个替代设计。

You are mixing up the datatypes. 您正在混合数据类型。

For example, when you test for the data you return integer 1. This will get translated to the data where sql server starts to count from + 1 (day) 例如,当您测试数据时,您返回整数 1.这将转换为sql server从+ 1(天)开始计数的数据

you can do 你可以做

select 
    case when mydate is null
    then '1' else cast(mydate as varchar(40))
    end,
    case when MyIs is null
    then 999 else MyIs
    end
from tab

在此输入图像描述

SQL servers "zero" date or base date is 1900-01-01 so you are just converting MYDate null with 1 so it is adding 1 day in base date as SQL服务器“零”日期或基准日期是1900-01-01,因此您只是将MYDate null转换为1,因此它在基准日期添加1天为

declare @d datetime = 1
select @d

1900-01-02 00:00:00.000

set @d = 0
select @d

1900-01-01 00:00:00.000

MyIs is a bit type so anything except 0 is '1' like MyIs有点类型,所以除0之外的任何东西都是'1'

declare @b bit = 0
select @b

set @b = 1
select @b

set @b = -1
select @b

Above behavior of columns because of different data types 由于data types不同,列的行为data types

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM