我正在尝试创建一个SQL脚本来循环遍历一个表,并检查AppID字段是否在另一个表中正确。然后,如果它在另一个表中找到记录,则会删除该行,并设置是否删除该变量。
到目前为止,我已经创建了循环,并在找到记录时设置了变量,但是我尝试添加delete语句,并且产生了一个错误,提示“ ELSE附近的语法不正确”错误消息
Use APTLive
Go
declare @RowNum int, @CustId nchar(5), @Name1 nchar(25)
declare @ProdCount int
declare @PROD nchar(5)
select @CustId=MAX(ID) FROM TempAppTable --start with the highest ID
Select @RowNum = Count(*) From TempAppTable --get total number of records
WHILE @RowNum > 0 --loop until no more records
BEGIN
select @Name1 = AppID from TempAppTable where ID = @CustID --get other info from that row
select @ProdCount = Count(*) from ProductType where AppRefID = @Name1 --GET APP COUNT ProductType
print cast(@RowNum as char(12)) + ' ' + @Name1 + ' ' + cast(@ProdCount as char(3))
If @ProdCount > 0 SET @PROD = 'Y' DELETE FROM ProductType WHERE AppRefID = @Name1 ELSE SET @PROD = 'N'
select top 1 @CustId=ID from TempAppTable where ID < @CustID order by ID desc
set @RowNum = @RowNum - 1
END
谁能让我知道为什么我收到此错误?是因为IF仅在返回true或false时才可以执行一项任务吗?
答案 0 :(得分:0)
由于您的BEGIN
条件,您错过了END
和IF
,因为您的IF包含多个指令,因此您需要在代码块中使用BEGIN&END
Use APTLive
Go
declare @RowNum int, @CustId nchar(5), @Name1 nchar(25)
declare @ProdCount int
declare @PROD nchar(5)
select @CustId=MAX(ID) FROM TempAppTable --start with the highest ID
Select @RowNum = Count(*) From TempAppTable --get total number of records
WHILE @RowNum > 0 --loop until no more records
BEGIN
select @Name1 = AppID from TempAppTable where ID = @CustID --get other info from that row
select @ProdCount = Count(*) from ProductType where AppRefID = @Name1 --GET APP COUNT ProductType
print cast(@RowNum as char(12)) + ' ' + @Name1 + ' ' + cast(@ProdCount as char(3))
If @ProdCount > 0
BEGIN -- [Added Mjoy]
SET @PROD = 'Y'
DELETE FROM ProductType WHERE AppRefID = @Name1
END -- [Added Mjoy]
ELSE SET @PROD = 'N'
select top 1 @CustId=ID from TempAppTable where ID < @CustID order by ID desc
set @RowNum = @RowNum - 1
END