例子:
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
Run Code Online (Sandbox Code Playgroud)
创建 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
Run Code Online (Sandbox Code Playgroud)
我收到错误:列名“xyz”无效。关于为什么 #temp 表版本在存储过程创建时不会抛出错误的任何想法?使用 SQL Server 2012,以防万一。
小智 5
它与延迟名称解析和编译有关。更多信息请参见:https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms190686(v=sql.105)
在编译时,临时表/变量不存在,因此该语句不会被编译。它会在执行时抛出错误。我知道,这很糟糕。
如果您先使用表变量运行该语句,而之前没有创建dbo.t1,它也不会抛出错误。
| 归档时间: |
|
| 查看次数: |
975 次 |
| 最近记录: |