1. 程式人生 > >Sql Server遊標使用 exec函式執行動態sql

Sql Server遊標使用 exec函式執行動態sql

資料表tb_HandledJobLog記錄的是已經處理過的資料,該資料錶行包含資料的實體類名欄位,根據實體類名可以找到這條資料屬於哪個表,然後根據找到的表可以找出每個表都有的欄位AccountIdAccountId即是這條資料的提交人,根據AccountId可以找到所屬公司。所以我在表tb_HandledJobLog添加了一個數據表缺少欄位ResponsibleOrgId來標記資料屬於哪個公司。接下來就使用遊標來處理以前的老資料,由於遊標用的比較少所以記錄下來以備查閱。

	declare @Id varchar(36)--已辦工作實體Id欄位
	declare @EntityId varchar(36)--實體Id欄位
	declare @TableName sysname --tablename欄位
        declare @sql NVARCHAR(4000) 
	
	declare unitCursor CURSOR for SELECT a.Id,EntityId,TableName from tb_HandledJobLog a LEFT JOIN dbo.tb_EntityClass b ON a.EntityName=b.EntityClassName
	open unitCursor
	Fetch next from unitCursor INTO @Id,@EntityId,@TableName
	while (@@fetch_status=0)
	BEGIN
		SET @sql=N'UPDATE dbo.tb_HandledJobLog SET ResponsibleOrgId=(select Id from tb_Organization where Code = (select  SUBSTRING( (select OrgCode FROM View_AccountOrganization where Id=(SELECT AccountId FROM '
[email protected]
+' WHERE Id='''[email protected]+''')),1,4))) WHERE dbo.tb_HandledJobLog.Id='''[email protected]+'''' EXEC(@sql) Fetch next from unitCursor into @Id,@EntityId,@TableName end close unitCursor deallocate unitCursor