示例:
create table dbo.t1 (id int)
if OBJECT_ID('dbo.s_Test') is not null drop proc dbo.s_Test
GO
create proc dbo.s_Test
as
create table #t2 (id2 int)
select t.id, t.xyz from dbo.t1 t join #t2 t2 on t2.id2 = t.id
GO
当创建 proc s_Test 时,我期待一个类似“无效的列名 'xyz'”的错误,但是在 proc 创建时没有错误。看来 #temp 表似乎与它有关,因为如果我使用表变量创建此版本:
if OBJECT_ID('dbo.s_Test2') is not null drop proc dbo.s_Test2
GO
create proc dbo.s_Test2
as
declare @t2 table (id2 int)
select t.id, t.xyz from dbo.t1 t join @t2 t2 on t2.id2 = t.id
GO
我收到错误:列名“xyz”无效。关于为什么 #temp 表版本在存储过程创建时不会抛出错误的任何想法? 使用 SQL Server 2012,以防万一。
最佳答案
它与延迟名称解析和编译有关。更多信息请点击:https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms190686(v=sql.105)
在编译时,临时表/变量不存在,因此该语句不会被编译。它会在执行时抛出错误。我知道,这很糟糕。
如果您先运行带有表变量的语句,而之前没有创建 dbo.t1,它也不会抛出错误。
关于sql-server - 使用 #temp 表时未检测到无效列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56847087/