如果表返回null,如何插入字符串?

时间:2015-02-10 20:52:11

标签: sql sql-server-2008 testing sql-insert

我正在尝试调整其他人写的查询以进行一些测试。此文件中有几个查询将提取数据,只要没有生成结果,那么一切都很好。这个查询中有几个我不理解的地方,但我唯一想知道的是如果没有生成结果我可以插入'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;

我真的很久才意识到,但我试着保持简单,只吃肉和土豆。我想知道的是,当查询从最后的表1-6中提取结果时,如果没有任何显示,我如何插入一个完全不同的表(例如ResultsTable),其值为pass / fail?

1 个答案:

答案 0 :(得分:1)

这种最简单的方法,虽然不是很优雅,但只是计算你创建的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');