如何在临时 table 中添加空值记录?

How to add a Null Value record in a temporary table?

我有一个 table 'AgentEventStats' 有特工 ID 和他们的名字。我在一个数据集中使用这个 table 来提取代理名称以使用统计报告的参数。 (这是为了 排除 我报告的代理人)。

但是,我到select该参数的代理,否则我的报告将无法工作。这意味着如果我不想排除任何代理,(NULL 值)我不能 运行 该报告。

所以,我想,我会在包含 AgentEventStats 记录的临时 table 中插入一个 Null 值。

我尝试了什么:

    SELECT DISTINCT AgentReporting, AgentFirstName + ' ' + AgentLastName [AgentName]
    INTO #AgentStats    -- First, creating the temp table.
    FROM AgentEventStats
    WHERE MidnightStartDate >= dateadd(day, -60, getdate())--'2017-01-01'
    AND MidnightStartDate <  getdate() --dateadd(day,1,'2017-03-13')
    ORDER BY AgentName

    INSERT INTO #AgentStats (AgentReporting, AgentName)  --Then, inserting the Null value in that temp table.
    VALUES ('100', 'No Agents');

这行不通。我收到一条错误消息:

There is already an object named '#AgentStats' in the database.

有人建议我改用 Union All。有人可以指导我吗?

如果您 运行 在同一个连接中多次使用类似的代码,您将收到该错误。

快速修复:将 DROP TABLE #AgentStats 添加到脚本末尾。

然后 运行 仅该行一次(降低温度 table)。

然后您可以 运行 一遍又一遍地执行整个脚本而不会出错。在删除之前添加一个 SELECT * FROM #AgentStats 以查看 table 中的内容,然后再删除它。

另一种方法是首先检查临时文件 table 是否存在,然后在 运行 执行脚本的其余部分之前将其删除。像这样:

IF OBJECT_ID('tempdb..#AgentStats') IS NOT NULL 
    DROP TABLE #AgentStats

SELECT DISTINCT...

如果你这样做,你将不再需要最后的 DROP TABLE

希望这对您有所帮助。

编辑

UNION 解决方案。

SELECT DISTINCT AgentReporting, AgentFirstName + ' ' + AgentLastName [AgentName]
FROM AgentEventStats
WHERE MidnightStartDate >= dateadd(day, -60, getdate())--'2017-01-01'
AND MidnightStartDate <  getdate() --dateadd(day,1,'2017-03-13')
UNION ALL -- added ALL based on comment
SELECT '100', 'No Agents'
ORDER BY 2;