如何在临时表中添加Null Value记录?

时间:2017-03-20 21:15:30

标签: reporting-services report

我有一个表'AgentEventStats',它有代理ID及其名称。我在数据集中使用此表,该数据集提取代理名称以使用Stats报告的参数。 (这是排除我的报告的代理商。)

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

所以,我想,我会在包含AgentEventStats记录的临时表中插入一个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');

这不起作用。我收到一条错误消息:

  

数据库中已有一个名为'#AgentStats'的对象。

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

1 个答案:

答案 0 :(得分:1)

如果您在同一个连接中运行代码不止一次,您将收到该错误。

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

然后只运行该行一次(删除临时表)。

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

另一种方法是首先检查临时表是否存在,然后在运行其余脚本之前删除它。像这样:

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;