使用INSERT时如何用值替换NULL?

时间:2019-01-28 01:19:04

标签: sql sql-server

我正试图找出为什么查询的这一部分不起作用

ISNULL(nightlyTable.AppointmentID, 
baseTable.AppointmentID) AS AppointmentID

还有另一种编写本节的方式吗?我需要它在值为NULL时显示一个AppointmentID。

谢谢!

USE [AdventureWorksLT]
GO

SET IDENTITY_INSERT [dbo].[tempTable] ON

INSERT INTO [dbo].[tempTable]
           ([AppointmentID]
           ,[CustName]
           ,[CustAddress]
           ,[CustPhone])

(SELECT 

    ISNULL(nightlyTable.AppointmentID, 
    baseTable.AppointmentID) AS AppointmentID

    , nightlyTable.CustName
    , nightlyTable.CustAddress
    , nightlyTable.CustPhone 
FROM nightlyTable
FULL OUTER JOIN  baseTable ON (baseTable.AppointmentID = 
nightlyTable.AppointmentID)
WHERE EXISTS (SELECT nightlyTable.* EXCEPT SELECT baseTable.*))
GO

SET IDENTITY_INSERT [dbo].[tempTable] OFF;

采样结果。我希望第10行显示AppointmentID'10'而不是NULL。

AppointmentID   CustName    CustAddress             CustPhone
 1              Salvad0r    1 Main Street North     76197081653
 NULL           NULL        NULL                    NULL
 3              Gilbert     51 Main Street South    23416310745
 NULL           NULL        NULL                    NULL
 5              Jorge       176 Washington Street   7078675309
 NULL           NULL        NULL                    NULL
 7              Stella      192 Church Street       78584836879
 NULL           NULL        NULL                    NULL
 9              Heyy        214 High Street         57288772686
 NULL           NULL        NULL                    NULL
 11             Newbie      21 Jump Street          76086753019

样本表:

enter image description here

2 个答案:

答案 0 :(得分:1)

此代码:

ISNULL(nightlyTable.AppointmentID, baseTable.AppointmentID) AS AppointmentID

不起作用,因为您没有basetable子句中定义的FROM的表别名。

答案 1 :(得分:0)

因此,您要选择基表中不在床头柜中的所有元素。为此,您将基本表连接到床头柜,然后查看无法连接的位置。像这样:

select b.*
from baseTable b
left join nightlyTable n on n.AppointmentID = b.AppointmentID
where n.AppointmentID is null

如果您还希望将现有数据包括在夜间表中,则简单的方法是使用联合,例如:

select *
from nightlyTable

UNION ALL

select b.*
from baseTable b
left join nightlyTable n on n.AppointmentID = b.AppointmentID
where n.AppointmentID is null