SQL 案例陈述 returns 错误的值

SQL Case statement returns wrong value

我有以下 sql 语句,它旨在在 t2.InventoryStatusCode 更改为 'p' 时为字段 t1.DWPostedDateKey 赋值。 t1.DWPostedDateKey 的起始值为 NULL,如果 t2.InventoryStatusCode 不变,我希望它保持 NULL。

select
t1.DateKey,
t1.DWPostedDateKey,
(CASE WHEN t2.InventoryStatusCode = 'p' 
             and (t1.InventoryStatusKey != t2.InventoryStatusKey) THEN 
     CONVERT(int, GetDate(), 112)
ELSE 
     t1.DWPostedDateKey
END)
from table1 t1 inner join
   table2 t2 on t1.key = t2.key

问题是我没有得到 NULL ?以下是结果示例:

DateKey     DWPostedDateKey   (No column name)
20150413    NULL              42106
20150413    NULL              42106
20150413    NULL              42106
20150413    20150414          20150414
20150413    20150414          20150414
20150413    20150414          20150414

42106 在里面做什么?我希望它保持 NULL 值。

问题出在这一行CONVERT(int, GetDate(), 112),具体在int

它将 datetime 转换为 int 和 SQL 服务器,当您这样做时 return 计算自 1/1/1900 以来的天数。 (就是你看到的数字)

这将return你所需要的
CONVERT(varchar, GetDate(), 112)

如果你需要一个整数试试这个
CAST(CONVERT(varchar, GetDate(), 112) AS INTEGER)

希望对您有所帮助

据我测试,您的 SQL 代码工作正常。在您的数据中,您似乎得到了一个 int 值而不是 NULL 值。

如果您 post 来自 table t1 和 t2 的行作为此结果集的基础,将会有所帮助。

但是,当我重现它时,当你在 t2 中更改 'InventoryStatus' 的值时,我只能让它在第三列中生成一个 int。

declare @table1 table (
    [key] int,
    DateKey nvarchar(8),
    DWPostedDateKey nvarchar(8),
    InventoryStatusKey int
)

declare @table2 table (
    [key] int,
    InventoryStatusKey int,
    InventoryStatusCode nvarchar(1)
)

insert into @table1 values (1, N'20150413', NULL, 1)
insert into @table1 values (2, N'20150413', NULL, 1)
insert into @table1 values (3, N'20150413', NULL, 1)
insert into @table1 values (4, N'20150413', N'20150414', 1)
insert into @table1 values (6, N'20150413', N'20150414', 1)

insert into @table2 values (1, 1, 'a')
insert into @table2 values (1, 2, 'a')
insert into @table2 values (3, 2, 'p') 
insert into @table2 values (4, 2, 'a')
insert into @table2 values (6, 1, 'a')

select
    t1.DateKey,
    t1.DWPostedDateKey,
    (CASE WHEN 
        t2.InventoryStatusCode = 'p' 
        and (t1.InventoryStatusKey != t2.InventoryStatusKey) 
     THEN 
        CONVERT(int, GetDate(), 112)
ELSE 
     t1.DWPostedDateKey
END)
from @table1 t1 inner join
   @table2 t2 on t1.[key] = t2.[key]

我将 InventoryStatusCode 的值从 'a' 更改为 'p',结果就是您得到的结果。