从SQL Server 2008 R2中的已连接表中删除一行

时间:2012-11-21 10:44:30

标签: sql sql-server tsql

我有两张桌子:

CREATE TABLE [Training].[UserTrainingModuleResults](
[UserTrainingModuleResultId] [int] IDENTITY(1,1) NOT NULL,
[TrainingModules_TrainingModuleId] [int] NOT NULL,
[Users_UserId] [int] NOT NULL,
[DateAndTimeStarted] [datetime] NOT NULL,
[DateAndTimeCompleted] [datetime] NULL,
[NumberOfQuestionsAnswered] [smallint] NOT NULL,
[NumberOfQuestionsAnsweredCorrectly] [smallint] NOT NULL,
[TrainingModuleStatuses_TrainingModuleStatusId] [smallint] NOT NULL,
  CONSTRAINT [PK_UserTrainingModuleResults] PRIMARY KEY CLUSTERED 
(
[UserTrainingModuleResultId] ASC
  )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,    ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

CREATE TABLE [History].[ViewTrainingModuleHistory](
[HistoryId] [int] NOT NULL,
[TrainingModules_TrainingModuleId] [int] NOT NULL,
CONSTRAINT [PK_ViewTrainingModuleHistory] PRIMARY KEY CLUSTERED 
(
[HistoryId] ASC
  )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
 ) ON [PRIMARY]

然后我有一个必须从ViewTrainingModuleHistory中删除的脚本,其中TrainingModules_TrainingModuleId = UserTrainingModuleResults.TrainingModules_TrainingModuleId

delete from History.TrainingModuleCompletedHistory as tmch  //syntax error here
  left join Training.UserTrainingModuleResults as utmr
on utmr.UserTrainingModuleResultId = tmch.UserTrainingModuleResults_UserTrainingModuleResultId
where utmr.Users_UserId = 446 and tmch.UserTrainingModuleResults_UserTrainingModuleResultId = 110

以上是不正确的,我在“as”附近得到语法错误 请帮忙 感谢

3 个答案:

答案 0 :(得分:1)

delete tmch  
from History.TrainingModuleCompletedHistory tmch
  left join Training.UserTrainingModuleResults utmr
on utmr.UserTrainingModuleResultId = tmch.UserTrainingModuleResults_UserTrainingModuleResultId
where utmr.Users_UserId = 446 and tmch.UserTrainingModuleResults_UserTrainingModuleResultId = 110

答案 1 :(得分:0)

别名应该在单词DELETE之后:

delete tmch   --- < alias of table to delete records from goes here
from History.TrainingModuleCompletedHistory tmch  
left join Training.UserTrainingModuleResults utmr
  on utmr.UserTrainingModuleResultId = tmch.UserTrainingModuleResults_UserTrainingModuleResultId
where utmr.Users_UserId = 446 
  and tmch.UserTrainingModuleResults_UserTrainingModuleResultId = 110

答案 2 :(得分:0)

delete tmch  
from History.TrainingModuleCompletedHistory tmch  
left join Training.UserTrainingModuleResults utmr
on utmr.UserTrainingModuleResultId = tmch.UserTrainingModuleResults_UserTrainingModuleResultId
where utmr.Users_UserId = 446 
and tmch.UserTrainingModuleResults_UserTrainingModuleResultId = 110