sql-server - 具有 IF 逻辑的 T-SQL 不适用于临时表

标签 sql-server tsql

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

IF OBJECT_ID('BIC_Analytics.dbo.AdjudicateAllDCCharteredClaims') IS  NULL
begin
select 'this is start of first block'
 SELECT 'this is first block' as blockid
 INTO #iftry
select 'this is end of first block'
end

ELSE

begin
select 'this is start of 2nd block'
 SELECT 'this is 2nd block' as blockid
    INTO #iftry
select 'this is end of 2nd block'
end

select ':)'

select * from #iftry

一直给我错误:

Msg 2714, Level 16, State 1, Line 18
There is already an object named '#iftry' in the database.

现在可以了

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

create table #iftry (blockid varchar(20))


IF OBJECT_ID('BIC_Analytics.dbo.AdjudicateAllDCCharteredClaims') IS NOT NULL
begin
--select 'this is start of first block'
 insert into #iftry (blockid)
 select 'this is first block' 
--select 'this is end of first block'
end

ELSE

begin
--select 'this is start of 2nd block'
 insert into #iftry (blockid)
 select 'this is 2nd block' 
--select 'this is end of 2nd block'
end

select ':)'

select * from #iftry

最佳答案

这是解析问题,不是运行时问题。 SQL Server 看不到有两个代码路径无法访问。

要解决它,请先创建一次#temp 表:

SELECT 'bogus' INTO #iftry
  WHERE 1 = 0; -- creates empty table

IF ...
  INSERT #iftry ...
ELSE ...
  INSERT #iftry ...

没有办法告诉 SQL Server 不要以这种方式工作,除非你将两个 #table 声明放在不同的批处理中(你不能真正这样做),或者构建动态 SQL 并在该范围内使用 #temp 表(不好玩)。

关于sql-server - 具有 IF 逻辑的 T-SQL 不适用于临时表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12408599/

相关文章:

sql-server - 如何在全文搜索中为不同列分配权重?

c# - C# 中的西里尔编码

sql - 根据 SQL Server 位置重新排序行

sql - 别名FOR XML PATH结果

tsql - SQL Server 中基于 FIFO 的库存估价

sql - 使用不同数据集的 UNION ORDER BY (T-SQL)

sql - 如何搜索包含JSON数组的SQL列

sql - 如何让SQL Server忽略检查?

sql-server - 合并重复值的行

sql-server - 在 PowerShell 中通过 SMO 执行 SQL 脚本时出错