我试图通过T-SQL
脚本更改特定表的架构。我想创建一个临时表,将相关数据转储到该表中,删除/重新创建原始表,然后传输数据。
只要我没有运行最终的INSERT
语句,脚本似乎工作正常。
INSERT INTO AgentRelationshipCodes(RelationshipId, EffectiveDate, LastChangeDate, LastChangeId, AgtTableId)
SELECT RelationshipId, EffectiveDate, LastChangeDate, LastChangeId, ID
FROM tmpAgentRelationshipCodes
此时我收到错误消息
Msg 207, Level 16, State 1, Line 26
Invalid column name 'AgtTableId'.
不知道为什么,因为我在第一个CREATE TABLE
语句中清楚地创建了这个字段。另外,如果我运行脚本的其余部分(基本上创建两个表,将数据转储到临时表中)和INSERT
语句分别运行它们。
CREATE TABLE tmpAgentRelationshipCodes
(
ID int,
RelationshipId char(3),
EffectiveDate datetime,
LastChangeDate datetime,
LastChangeId char(6)
);
INSERT INTO tmpAgentRelationshipCodes(ID, RelationshipId, EffectiveDate, LastChangeDate, LastChangeId)
SELECT ID, RelationshipId, EffectiveDate, LastChangeDate, LastChangeId
FROM AgentRelationshipCodes
DROP TABLE AgentRelationshipCodes
CREATE TABLE AgentRelationshipCodes
(
Id UNIQUEIDENTIFIER DEFAULT NEWID(),
RelationshipId char(3) NULL,
EffectiveDate datetime NULL,
LastChangeDate datetime NOT NULL,
LastChangeId char(6) NOT NULL,
AgtTableId int FOREIGN KEY REFERENCES AgentTransmission(ID)
);
INSERT INTO AgentRelationshipCodes(RelationshipId, EffectiveDate, LastChangeDate, LastChangeId, AgtTableId)
SELECT RelationshipId, EffectiveDate, LastChangeDate, LastChangeId, ID
FROM tmpAgentRelationshipCodes
答案 0 :(得分:0)
按如下方式编辑脚本以包含[dbo],并且还需要GO
语句来分隔命令。
CREATE TABLE [dbo].[tmpAgentRelationshipCodes]
(
ID int,
RelationshipId char(3),
EffectiveDate datetime,
LastChangeDate datetime,
LastChangeId char(6)
);
GO
INSERT INTO [dbo].[tmpAgentRelationshipCodes](ID, RelationshipId, EffectiveDate, LastChangeDate, LastChangeId)
SELECT ID, RelationshipId, EffectiveDate, LastChangeDate, LastChangeId
FROM [dbo].[AgentRelationshipCodes]
GO
DROP TABLE [dbo].[AgentRelationshipCodes]
CREATE TABLE [dbo].[AgentRelationshipCodes]
(
Id int PRIMARY KEY,
RelationshipId char(3) NULL,
EffectiveDate datetime NULL,
LastChangeDate datetime NOT NULL,
LastChangeId char(6) NOT NULL,
AgtTableId int FOREIGN KEY REFERENCES AgentTransmission(ID)
ON DELETE CASCADE
)
GO
INSERT INTO [dbo].[AgentRelationshipCodes](RelationshipId, EffectiveDate, LastChangeDate, LastChangeId, AgtTableId)
SELECT RelationshipId, EffectiveDate, LastChangeDate, LastChangeId, ID
FROM [dbo].[tmpAgentRelationshipCodes]