如果 table returns 为空,如何插入字符串?

How to insert a string if a table returns null?

我正在尝试改编其他人编写的查询以进行一些测试。此文件中有几个查询将提取数据,只要没有生成结果,那么一切都很好。此查询中有几个地方我不明白,但我真正想知道的是如果没有生成结果,我如何插入 'PASS' 或 'FAIL' 值。

declare @i int, @d nvarchar (3), @max int, @db nvarchar (100), 
@query nvarchar (max), @base_db_name nvarchar(50), @use_loop int;

select name
from sys.databases


IF OBJECT_ID('tempdb..#TABLE1') IS NOT NULL
BEGIN
    DROP TABLE #TABLE1
END

create table #TABLE1 (
    Column1 datatype,
    Column2 datatype,
    Column3 datatype,

IF OBJECT_ID('tempdb..#TABLE2') IS NOT NULL
BEGIN
    DROP TABLE #TABLE2
END

create table #TABLE2 (
    Column1 datatype,
    Column2 datatype,
    Column3 datatype,
    )   

IF OBJECT_ID('tempdb..#TABLE3') IS NOT NULL
BEGIN
    DROP TABLE #TABLE3
END

create table #TABLE3 (
    Column1 datatype,
    Column2 datatype,
    Column3 datatype,
    )

IF OBJECT_ID('tempdb..#TABLE4') IS NOT NULL
BEGIN
    DROP TABLE #TABLE4
END

create table #TABLE4 (
    Column1 datatype,
    Column2 datatype,
    Column3 datatype,
    )


IF OBJECT_ID('tempdb..#TABLE5') IS NOT NULL
BEGIN
    DROP TABLE #TABLE5
END

create table #TABLE5 (
    Column1 datatype,
    Column2 datatype,
    Column3 datatype,
    )

IF OBJECT_ID('tempdb..#TABLE6') IS NOT NULL
BEGIN
    DROP TABLE #TABLE6
END

create table #TABLE6 (
    Column1 datatype,
    Column2 datatype,
    Column3 datatype,
    )



While @i <= @max
Begin
    if @use_loop = 1    
    Begin   
        set @d = CAST(@i as nvarchar);
        Set @db = @base_db_name +@d+ '].dbo.'; 
    End


Set @query = cast('
    *QUERY GOES HERE*
    ' as nvarchar(max))
Insert INTO #TABLE1
Execute (@query)


Set @query = cast('
    *QUERY GOES HERE*
    ' as nvarchar(max))
Insert INTO #TABLE2
Execute (@query)


Set @query = cast('
    *QUERY GOES HERE*
    ' as nvarchar(max))
Insert INTO #TABLE3
Execute (@query)

Set @query = cast('
    *QUERY GOES HERE*
    ' as nvarchar(max))
Insert INTO #TABLE3
Execute (@query)


Set @query = cast('
    *QUERY GOES HERE*
    ' as nvarchar(max))
Insert INTO #TABLE4
Execute (@query)


Set @query = cast('
    *QUERY GOES HERE*
    ' as nvarchar(max))
Insert INTO #TABLE5
Execute (@query)


Set @query = cast('
    *QUERY GOES HERE*
        ' as nvarchar(max))
    Insert INTO #TABLE6
    Execute (@query)



    set @i = @i + 1;
End
GO

Select *
from #TABLE1;

Select *
from #TABLE2;

Select *
from #TABLE3;

Select *
from #TABLE4;

Select *
from #TABLE5;

Select *
from #TABLE6;

我意识到它真的很长,但我尽量保持简单,只得到肉和土豆。我想知道的是,当查询最后从 tables 1-6 中提取结果时,如果什么都没显示?

这个最简单的方法,虽然公认并不优雅,但就是计算您创建的 6 个表中的记录数:

IF ((SELECT COUNT(*) FROM #Table1)
  + (SELECT COUNT(*) FROM #Table2)
  + (SELECT COUNT(*) FROM #Table3)
  + (SELECT COUNT(*) FROM #Table4)
  + (SELECT COUNT(*) FROM #Table5)
  + (SELECT COUNT(*) FROM #Table6)) > 0
  INSERT INTO ResultsTable (FieldName) VALUES ('Fail');
ELSE
  INSERT INTO ResultsTable (FieldName) VALUES ('Pass');