我在存储过程中使用游标;我希望从我的 SP 中删除光标。请帮我想出一个解决方案,以解决如何避免游标语句使用动态的正常更新语句。
下面的例子:
Update Tablename set columnname(variable) = value from table A join Table B on A.condition = B.Condition where name = 'Test'(variable) and age = 18(variable)
Update Tablename set columnname(variable) = value from table A join Table B on A.condition = B.Condition where name = 'kumar'(variable) and age = 19(variable)
Update Tablename set columnname(variable) = value from table A join Table B on A.condition = B.Condition where name = 'babu'(variable) and age = 30(variable)
这就是我的光标的工作方式。300组合动态从表中挑选数据并更新到主表中
我试图取出游标,更新语句应该与此类似,而不是编写 300 个更新语句,我想编写一个更新,所有 300 个组合都应该执行。
以下是我需要此解决方案的代码:
BEGIN
DECLARE @Type VARCHAR(100)
DECLARE @TargetColumn VARCHAR(100)
DECLARE @SourceColumn VARCHAR(100)
DECLARE @SQL varchar(max)
DECLARE a_cursor CURSOR STATIC
FOR
SELECT [Type],[SourceColumn],[TargetColumn] FROM ref.tblEdsMap
GROUP BY [Type],[SourceColumn],[TargetColumn]
OPEN a_cursor
FETCH NEXT FROM a_cursor INTO @Type,@SourceColumn,@TargetColumn
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQL = 'UPDATE GCT SET GCT.' + @TargetColumn + ' = map.[TargetValue]
from EdsMap map
JOIN Table GCT
ON GCT.' + @SourceColumn + ' = map.[SourceValue]
where map.[Type]=''' + @Type + ''' and map.SourceColumn=''' + @SourceColumn+ ''''
Exec (@SQL)
PRINT @SQL
FETCH NEXT FROM a_cursor INTO @Type,@SourceColumn,@TargetColumn
END
CLOSE a_cursor
DEALLOCATE a_cursor
END