表格类型无法正常工作的光标

时间:2015-06-05 14:44:04

标签: c# sql-server

这是我的光标

将表类型传递给游标以更新表列。

DECLARE cur CURSOR FOR SELECT * FROM @AutoDataType 
OPEN cur    
FETCH NEXT FROM cur INTO @Customer_Id,@First_Name
WHILE @@FETCH_STATUS = 0 
BEGIN           
  UPDATE [dbo].[ABC] SET [Customer_Id] =@Customer_Id            
  WHERE LOWER([PH_FirstName])=LOWER(@First_Name)                    
  FETCH NEXT FROM cur INTO @Customer_Id,@First_Name
END
CLOSE cur    
DEALLOCATE cur

当我尝试从查询窗口执行此游标时,如下所示,它可以正常工作

Declare @AutoDataType As [dbo].[Auto_DataType]
Insert Into @AutoDataType(Customer_Id,First_Name) Values('11111','JOHN');
Exec sp_TEST @AutoDataType

但是通过C#代码它不起作用,也没有错误。

我在这里做错了什么?

这是我的表类型:

CREATE TYPE [dbo].[Auto_DataType] AS TABLE([Customer_Id] [varchar](50) NULL,
                                           [First_Name] [varchar](50) NULL)

这是我的存储过程:

CREATE PROCEDURE [dbo].[sp_TEST](@AutoDataType As [dbo].[Auto_DataType] Readonly)
AS
Begin
DECLARE @Row_Id Int;
DECLARE @Customer_Id Varchar(50);
DECLARE @First_Name Varchar(50);
DECLARE @Last_Name Varchar(50);
DECLARE @DOB Varchar(50);
DECLARE @License_Number Varchar(50);
DECLARE @TransId VARCHAR(50);   
DECLARE @TimeStamp DATETIME;    
DECLARE cur CURSOR FOR SELECT * FROM @AutoDataType 
OPEN cur    
FETCH NEXT FROM cur INTO @Customer_Id,@First_Name
WHILE @@FETCH_STATUS = 0 
    BEGIN           
        UPDATE [dbo].[ABC] SET [Customer_Id]  =@Customer_Id            
        WHERE LOWER([PH_FirstName])=LOWER(@First_Name)   
        FETCH NEXT FROM cur INTO @Customer_Id,@First_Name
    END
CLOSE cur    
DEALLOCATE cur  
End

1 个答案:

答案 0 :(得分:0)

这里根本不需要光标。这应该是一个单独的更新声明。

UPDATE a SET [Customer_Id] = adt.Customer_Id            
FROM @AutoDataType adt
JOIN [dbo].[ABC] a on a.PH_FirstName = adt.First_Name
WHERE LOWER(a.[PH_FirstName]) = LOWER(adt.First_Name)   

请注意,除非您具有区分大小写的排序规则,否则此处的谓词无意义。就像在你的代码中一样,它会更新行,即使它们不是同一个案例。我建议只删除where子句。