我创建了一个存储过程,该过程验证了以表作为参数的某些列,并决定使用Cursor。但是在尝试执行存储过程时出现了此游标提取错误。
我已经仔细检查了列,它与INTO列表中的变量数匹配。我尝试通过编写
来修改存储过程SELECT Lot, ItemId, PO, Status, ErrorDetails
FROM Table1
代替
SELECT @SQLSTATEMENT
之后
SET @MyCursor = CURSOR FOR
,效果很好。但是我希望源表是一个参数,所以这对我不起作用。有什么想法吗?
CREATE PROCEDURE [dbo].[ValidateData]
@TABLENAME_PARAM NVARCHAR(100)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @MyCursor CURSOR;
DECLARE @CustomerLot NVARCHAR(100),
@DeviceName NVARCHAR(100),
@PO NVARCHAR(100),
@Status NVARCHAR(1),
@ErrorDetails NVARCHAR(250);
DECLARE @TABLENAME NVARCHAR(100);
DECLARE @SQLSTATEMENT AS NVARCHAR(MAX);
SELECT @TABLENAME = Quotename (TABLE_NAME)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = @TABLENAME_PARAM
SET @SQLSTATEMENT = 'Select Lot, ItemId, PO, Status, ErrorDetails FROM ' + @TABLENAME + ' WHERE Status = ''N'''
BEGIN
SET @MyCursor = CURSOR FOR
SELECT @SQLSTATEMENT
OPEN @MyCursor
FETCH NEXT FROM @MyCursor INTO @CustomerLot, @DeviceName, @PO, @Status, @ErrorDetails
WHILE @@FETCH_STATUS = 0
BEGIN
BEGIN TRAN
--some validations here
COMMIT TRAN
FETCH NEXT FROM @MyCursor INTO @CustomerLot, @DeviceName, @PO, @Status, @ErrorDetails
END;
CLOSE @MyCursor;
DEALLOCATE @MyCursor;
END
END
GO
答案 0 :(得分:0)
试试这个-
CREATE PROCEDURE [dbo].[ValidateData] @TABLENAME_PARAM NVARCHAR(100)
AS
BEGIN
SET NOCOUNT ON;
--DECLARE @MyCursor CURSOR;
DECLARE
@CustomerLot NVARCHAR(100),
@DeviceName NVARCHAR(100),
@PO NVARCHAR(100),
@Status NVARCHAR(1),
@ErrorDetails NVARCHAR(250);
DECLARE @TABLENAME NVARCHAR(100);
DECLARE @SQLSTATEMENT AS NVARCHAR(MAX);
SELECT @TABLENAME = Quotename (TABLE_NAME)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = @TABLENAME_PARAM
SET @SQLSTATEMENT = 'DECLARE MyCursor CURSOR FOR Select Lot, ItemId, PO, Status, ErrorDetails FROM ' + @TABLENAME + ' WHERE Status = ''N'''
EXEC sp_executesql @sqlstatement
OPEN MyCursor
FETCH NEXT FROM MyCursor INTO @CustomerLot, @DeviceName, @PO, @Status, @ErrorDetails
WHILE @@FETCH_STATUS = 0
BEGIN
BEGIN TRAN
--some validations here
COMMIT TRAN
FETCH NEXT FROM MyCursor INTO @CustomerLot, @DeviceName, @PO, @Status, @ErrorDetails
END;
CLOSE MyCursor;
DEALLOCATE MyCursor
END
END
GO