Sql-Server

檢查 Null 時,日期列上的計算列操作數類型沖突

  • October 19, 2019

嘗試使用Date欄位的計算列創建表時會生成此錯誤。

操作數類型沖突:int 與日期不兼容

如果我註釋掉計算列,它就可以工作。

[DateInActive][Date] NULL,             -- Date origination
[IsValid] AS (IsNull(DateInActive, 1)) -- Failure here

on 的想法IsValid是簡單地為該欄位返回一個biton|off 以表示沒有報告非活動日期,如果是,則它是有效的。

該列最終將For JSON作為is-a欄位傳遞到輸出中的 JSON,以供 SQL 外部使用。


完整的 SQL

CREATE TABLE [history].[PhoneBook](
   [PhoneBookId] [int] IDENTITY(1,1) NOT NULL,
   [PersonId] [int] NOT NULL,
   [PhoneId] [int] NOT NULL,
   [DateActive][Date] NOT NULL,
   [DateInActive][Date] NULL,
   [IsValid] AS (IsNull(DateInActive, 1))
CONSTRAINT [PK_PhoneBook_1] PRIMARY KEY CLUSTERED 
(
   [PersonId] ASC,
   [PhoneId] ASC

)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, 
      ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

根據ISNULL文件,返回的數據類型與檢查表達式的類型相同,date在這種情況下是數據類型。表達式失敗,ISNULL因為整數文字 1 不能隱式轉換為日期。

要返回一個指示日期列是否為 的位NULL,您可以改用 CASE 表達式:

CREATE TABLE [history].[PhoneBook](
   [PhoneBookId] [int] IDENTITY(1,1) NOT NULL,
   [PersonId] [int] NOT NULL,
   [PhoneId] [int] NOT NULL,
   [DateActive][Date] NOT NULL,
   [DateInActive][Date] NULL,
   [IsValid] AS CASE WHEN DateInActive IS NULL THEN CAST(0 AS BIT) ELSE CAST(1 AS bit) END
CONSTRAINT [PK_PhoneBook_1] PRIMARY KEY CLUSTERED 
(
   [PersonId] ASC,
   [PhoneId] ASC

)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, 
      ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

引用自:https://dba.stackexchange.com/questions/251517