我创建了一个包含 2 列的表格,然后我更改了表格并添加了第三列 ManagerID
已成功添加。
但是当我在查询中调用它时,出现此错误:
<块引用>无效的列名
代码:
-- This is example from the start.. please read it and tell me
CREATE DATABASE PortEmp
CREATE TABLE Employees
(
ID INT IDENTITY PRIMARY KEY,
Name VARCHAR(50) NOT NULL,
Salary INT NOT NULL,
)
-- Now I executed the code and table and database is added successfully
ALTER TABLE Employees
ADD ManagerID INT NOT NULL
-- Now I executed the alter command and it's been added
SELECT Name FROM Employees
-- I use select for name successfully
SELECT ManagerID FROM Employees
-- Now there is a red line under managerID
答案 0 :(得分:0)
错误发生在编译代码期间。 T-SQL 在执行之前编译一个批处理。在编译阶段,所有标识符都被解析。
所有三行都在同时编译。第三条语句失败,因为第二条语句——尽管编译还没有被执行——所以该列不存在。
一种解决方案是动态 SQL:
SELECT FirstName FROM Employee;
ALTER TABLE Employee ADD ManagerID INT NULL;
EXEC sp_executesql N'SELECT ManagerID FROM Employee';
动态 sql 在执行之前不会编译表达式——所以前面的所有语句都已经编译并执行。
将 GO
放在语句之间也应该起作用:
SELECT FirstName FROM Employee;
ALTER TABLE Employee ADD ManagerID INT NULL;
GO
SELECT ManagerID FROM Employee';
答案 1 :(得分:0)
批处理编译时,该列不存在。所以在下一批之前你不能引用它,通常用GO
分隔。
每个批处理或存储过程在执行开始时都由 SQL Server 编译,因此您会收到编译错误。
或者,您可以通过动态 SQL 执行查询的下一部分,如下所示:
DECLARE @sql nvarchar(max) = N'
SELECT 1; -- or whatever
-- don't forget this is text, not code, and you need to escape quotes
-- for example:
SELECT ''hello'';
-- Do also use parameters properly, like so:
SELECT @myParam;
';
EXEC sp_executesql @sql, N'@myParam varchar(20)', @myParam = @myParam;