Transact SQL:ISNULL返回空

时间:2019-01-09 11:26:39

标签: sql-server tsql

我的SQL Server 2017中具有下表:

CREATE TABLE [dbo].[sync_versions](
    [id] [bigint] IDENTITY(1,1) NOT NULL,
    [id_device_type] [bigint] NOT NULL,
    [version_stamp] [nvarchar](50) NOT NULL,
    [update_date] [datetime2](7) NULL,
 CONSTRAINT [PK_sync_versions] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[sync_versions] ADD  DEFAULT (getdate()) FOR [update_date]
GO

ALTER TABLE [dbo].[sync_versions]  WITH CHECK ADD  CONSTRAINT [FK_sync_versions_device_type] FOREIGN KEY([id_device_type])
REFERENCES [dbo].[device_types] ([id])
GO

ALTER TABLE [dbo].[sync_versions] CHECK CONSTRAINT [FK_sync_versions_device_type]
GO

该表当前不包含任何数据。但是,以下查询不返回任何内容。

select isnull([version_stamp],'0x0000000000000001') as [version_stamp]
from [dbo].[sync_versions]
where [id_device_type] = 2;

我希望该查询返回0x0000000000000001,对吗?如果是这样,如果表中没有数据,是否还有其他方法可以返回默认值?

亲切的问候。

1 个答案:

答案 0 :(得分:8)

如果表中没有数据,您将收到0行。因此,您需要包装查询:

ISNULL(
    (select [version_stamp]
    from [dbo].[sync_versions]
    where [id_device_type] = 2),
'0x0000000000000001')