我有一个如下表:
存档:
TableName ColumnName Datatype NewValue
Employee FirstName nvarchar Abc
Employee LastName nvarchar Pqr
Employee Age int 28
Address City nvarchar Chicago
Address StreetName nvarchar KKKKK
我正在尝试为每个表创建动态更新语句,并希望为每个单独的表执行更新语句,并在任何更新失败时进行回滚。
每个单独表的预期更新语句查询:
Update Employee set FirstName = 'Abc', LastName = 'Pqr', Age = 21
where DepartmentId = 100;
Update Address set City = 'Chicago', StreetName = 'KKKKK'
where DepartmentId = 100;
存储过程:
Alter PROC [dbo].[UpdateDataByDeptID]
@departmentId int
As
Begin
Declare db_cursor CURSOR for select TableName from Archival
group by TableName
Declare @tableName nvarchar(50),
@columnName nvarchar(50),
@datatype nvarchar(50),
@newValue nvarchar(50)
open db_cursor
Fetch Next from db_cursor into @tableName;
While @@FETCH_STATUS = 0
Begin
select @columnName = ColumnName,
@datatype = Datatype,
@newValue = NewValue
from Archival where TableName = @tableName;
print @tableName + ' ' + @columnName + ' ' + @newValue
Fetch Next from db_cursor into @tableName
End;
close db_cursor;
DEALLOCATE db_cursor;
Begin Transaction
Begin Try
--execute each of the update statement like below for ex:
Update Employee .....
Update Address .....
Commit transaction
End Try
Begin Catch
Rollback
End Catch
End
End -- end of SP
但问题是这一行:
print @tableName + ' ' + @columnName + ' ' + @newValue
上面一行给出了每个表的最后一条记录。例如,对于Employee
表:
Employee Age int 28
因此,我无法为每个表生成单独的更新语句。
对于我的事务,在对每个单独的表执行每个update语句后,最终的预期输出如下:
Begin Transaction
Begin Try
--execute each of the update statement like below for ex:
Update Employee set FirstName = 'Abc', LastName = 'Pqr', Age = 21
where DepartmentId = 100;
Update Address set City = 'Chicago', StreetName = 'KKKKK'
where DepartmentId = 100;
Commit transaction
End Try
Begin Catch
Rollback
End Catch
End
有人能帮我吗?
1条答案
按热度按时间fnatzsnv1#
如何 实现 这 一 点 的 一 个 示例 是 使用 动态 SQL 。
例如 :
中 的 每 一 个
我 相信 这 会 让 你 的 预期 产出 有所 提高 。
如果 您 不能 信任 NewValue 列 中 的 内容 , 那么 在 执行 此类 操作 时 , 我 会 非常 小心 。 ( 例如 , 如果 有人 可能 会 输入 某种 恶意 SQL , 并 在 此处 执行 ) 。