C# 如果原始表为空,请从其他表中选择

C# 如果原始表为空,请从其他表中选择,c#,sql-server,tsql,C#,Sql Server,Tsql,如果第一个表为空,如何使查询能够从另一个表中进行选择 这是我的C程序中的当前查询,我使用的是SQL Server private const string sql = @'SELECT TOP (1) (LOCALTIME) from dbo.[devicemessage] order by (localtime) desc; 因此,这段代码的作用是从localtime desc中排列的前1行获取localtime列中的值;最新时间 我想做的是这样的: If dbo.[devicemessag

如果第一个表为空,如何使查询能够从另一个表中进行选择

这是我的C程序中的当前查询,我使用的是SQL Server

private const string sql = @'SELECT TOP (1) (LOCALTIME) from dbo.[devicemessage] order by (localtime) desc;
因此,这段代码的作用是从localtime desc中排列的前1行获取localtime列中的值;最新时间

我想做的是这样的:

If dbo.[devicemessage] is empty select top (1) (localtime) from dbo.[devicemessagehistory] order by (localtime) desc,
if table dbo.[devicemessage] not empty, get from dbo.[devicemessage].

当我在C中使用它时,是否可以在一个查询字符串中执行此操作。

只需将两个表与一个not exists条件合并即可。这允许您从同一查询中的两个表中进行选择,但仅当第一个表中不存在行时,才会从第二个表中给出结果:

select top 1 localtime
from (
  select localtime
  from dbo.[devicemessage]
  union all
  select localtime
  from dbo.[devicemessagehistory]
  where not exists (select 1 from dbo.[devicemessage])
) X
order by localtime desc;

只需将这两个表与not exists条件合并在一起即可。这允许您从同一查询中的两个表中进行选择,但仅当第一个表中不存在行时,才会从第二个表中给出结果:

select top 1 localtime
from (
  select localtime
  from dbo.[devicemessage]
  union all
  select localtime
  from dbo.[devicemessagehistory]
  where not exists (select 1 from dbo.[devicemessage])
) X
order by localtime desc;
选择isnull或coalesce将获取您的最大DeviceMessageLocalTime(如果可用),如果不可用,将选择您的devicemessagehistory

如果只有2个条件,isnull就足够了,但是如果有多个条件,我建议使用coalesce

按顺序使用

选择isnull或coalesce将获取您的最大DeviceMessageLocalTime(如果可用),如果不可用,将选择您的devicemessagehistory

如果只有2个条件,isnull就足够了,但是如果有多个条件,我建议使用coalesce

按顺序使用


对于使用isnull还是coalesce,您有什么建议?Hardy需要提供两个选项,即您喜欢的选项。按localtime desc选择前1个localtime顺序,与选择相同maxlocaltime@Metalcoalesce也是ANSI SQL标准,而isnull是特定于SQL Server的。对于使用isnull还是coalesce,您有什么建议?Hardy需要提供两个选项,即您喜欢的选项。按localtime desc选择前1个localtime顺序,与选择相同maxlocaltime@Metalcoalesce也是ANSI SQL标准,而isnull是特定于SQL Server的。
select isnull(
    (select TOP 1 localtime from dbo.[devicemessage] order by localtime desc),
        (select TOP 1 localtime from dbo.[devicemessagehistory] order by localtime desc))