我在ms sql server中使用游标
DECLARE @LineOfAuthoritySubString varchar(100);
declare @tbProductId int;
declare @tbLineOfAuthorityId int;
DECLARE @MyCursor CURSOR
SET @MyCursor = CURSOR FAST_FORWARD
FOR
Select TempLineOfAuthority FROM #tbTempLineOfAuthority
OPEN @MyCursor
FETCH NEXT FROM @MyCursor
INTO @LineOfAuthoritySubString
WHILE @@FETCH_STATUS = 0
BEGIN
Set @tbLineOfAuthorityId = (Select LineOfAuthority
from tbLineOfAuthority where LineOfAuthorityX = @LineOfAuthorityNameSubString);
INSERT INTO tbProductLineOfAuthority(ProductId, LineOfAuthortyId)
VALUES(@tbProductId, @tbLineOfAuthorityId);
FETCH NEXT FROM @MyCursor
INTO @LineOfAuthoritySubString
END
CLOSE @MyCursor
DEALLOCATE @MyCursor
它不起作用。它将null值赋给变量@tbLineOfAuthorityId。
答案 0 :(得分:2)
您正在@LineOfAuthoritySubString
和中使用条件 @LineOfAuthorityNameSubString
变量中插入游标值
两个变量名都不匹配。
FETCH NEXT FROM @MyCursor INTO @LineOfAuthoritySubString
IN上面你在变量@LineOfAuthoritySubString中获取值。
Set @tbLineOfAuthorityId = (Select LineOfAuthority from tbLineOfAuthority where LineOfAuthorityX = @LineOfAuthorityNameSubString);
但是当您从表tbLineOfAuthority中选择时,请在查询的位置观察您使用的变量。
应该 @LineOfAuthoritySubString 而不是 @LineOfAuthorityNameSubString
请在编辑后的查询下方尝试。
DECLARE @LineOfAuthoritySubString varchar(100);
declare @tbProductId int;
declare @tbLineOfAuthorityId int;
DECLARE @MyCursor CURSOR
SET @MyCursor = CURSOR FAST_FORWARD
FOR
Select TempLineOfAuthority FROM #tbTempLineOfAuthority
OPEN @MyCursor
FETCH NEXT FROM @MyCursor
INTO @LineOfAuthoritySubString
WHILE @@FETCH_STATUS = 0
BEGIN
Set @tbLineOfAuthorityId = (Select LineOfAuthority
from tbLineOfAuthority where LineOfAuthorityX = @LineOfAuthoritySubString);
INSERT INTO tbProductLineOfAuthority(ProductId, LineOfAuthortyId)
VALUES(@tbProductId, @tbLineOfAuthorityId);
FETCH NEXT FROM @MyCursor
INTO @LineOfAuthoritySubString
END
CLOSE @MyCursor
DEALLOCATE @MyCursor