根据查询结果 returns 将字符串插入 SQL table

Inserting strings into an SQL table depending on what results a query returns

我有一些查询用于测试我 运行 测试的数据库结果是否没有任何明显的损坏和错误。

其中一个查询具有以下基本形式:

SELECT *
FROM Table
WHERE Column = ''

它正在检查以确保某一特定字段不为空。我想跟踪这些测试 运行 以及它们何时通过或失败。有没有一种方法可以让我编写一个查询,这样如果该查询返回任何结果,它就会将一个字符串写入另一个 table,类似于 "Test Passed"?

因此,伪版本可能如下所示:

IF (
    SELECT *
    FROM Table1
    WHERE Table1.Column1 = ''
) = 0
INSERT INTO Table2 (FileName, Date, Result)
VALUES ('File1', 'GetDate()', 'Test Passed')
ELSE
INSERT INTO Table2 (FileName, Date, Result)
VALUES ('File1', 'GetDate()', 'Test Failed')

table 可能如下所示:

| FileName |   Date   |    Result   |
|:--------:|:--------:|:-----------:|
| File1    | 12-25-16 | Test Passed |
| File2    | 12-25-16 | Test Failed |
| File3    | 12-25-16 | Test Passed |
| File4    | 12-25-16 | Test Passed |

你几乎已经在你的代码中了。只需将 SELECT * 更改为 SELECT COUNT(*) 即可。我会设置状态然后进行插入。

DECLARE @testStatus NVARCHAR(MAX);

IF (
    SELECT COUNT(*)
    FROM Table1
    WHERE Table1.Column1 = ''
) = 0
    SET @testStatus = 'Test Passed'
ELSE
    SET @testStatus = 'Test Failed'

INSERT INTO Table2 (FileName, Date, Result)
VALUES ('File1', GetDate(), @testStatus)

Is there a way that I can write a query so that if that query brings back any results then it writes a string to another table that says something like "Test Passed"?

进一步构建您的查询,您可以执行如下操作

--无列所以测试通过

    IF not exists ( SELECT *
        FROM Table1
        WHERE Table1.Column1 = ''
    ) 
Begin
    INSERT INTO Table2 (FileName, Date, Result)
    VALUES ('File1', 'GetDate()', 'Test Passed')
End

如果你只想通过查询(没有 T-SQL)获得结果,你可以使用这个解决方案:

INSERT INTO Table2(FileName, Date, Result)
  SELECT 'File1', GetDate(), X.Result FROM (
    SELECT 'Test passed' Result
       WHERE EXISTS(SELECT * FROM Table1 WHERE Column1 = '')
    UNION ALL      
    SELECT 'Test failed'
       WHERE NOT EXISTS (SELECT * FROM Table1 WHERE Column1 = '')
  ) X

稍加努力,您也可以编写相同查询的 Oracle 版本:

INSERT INTO Table2(FileName, Date, Result)
  SELECT 'File1', sysdate, X.Result FROM (
    SELECT 'Test passed' Result FROM dual
       WHERE EXISTS(SELECT * FROM Table1 WHERE Column1 = '')
    UNION ALL      
    SELECT 'Test failed' FROM dual
       WHERE NOT EXISTS (SELECT * FROM Table1 WHERE Column1 = '')
  ) X
MERGE 
   table2 AS target
USING 
   table1 AS source
ON 
   source.Column1 = ''
WHEN MATCHED THEN 
   INSERT INTO target (FileName, Date, Result)
   VALUES ('File1', 'GetDate()', 'Test Failed')
WHEN NOT MATCHED THEN 
   INSERT INTO target (FileName, Date, Result)
   VALUES ('File1', 'GetDate()', 'Test Passed')