﻿CREATE PROC [dbo].[SP_DataIdMove]
		@exTable NVARCHAR(50) = NULL ,
		@colums NVARCHAR(50) = NULL	,
		@trueId NVARCHAR(50) = NULL	
		--,@returnVal int output
AS

BEGIN
--DECLARE @returnVal int =0
--SET @returnVal = 0
DECLARE @OldId nvarchar(50),@NewId nvarchar(50)
DECLARE @tablename nvarchar(1000),@columnname nvarchar(1000)
DECLARE @sql nvarchar(2000) 
DECLARE cursor_Id CURSOR FOR -- 定义游标
   SELECT OldId ,NewIds FROM DataIdMove WHERE ColumType = @colums and NewIds = @trueId
   OPEN cursor_Id
   FETCH NEXT FROM cursor_Id INTO  @OldId,  @NewId -- 抓取下一行游标数据
   WHILE @@FETCH_STATUS = 0     --(-1 语句失败， -2 被提取行不存在）
      BEGIN			
	    --SET @returnVal=@returnVal+1
		--print @OldId
		DECLARE cursor_name CURSOR FOR -- 定义游标
		SELECT DISTINCT TABLE_NAME,COLUMN_NAME
		FROM INFORMATION_SCHEMA.COLUMNS
		WHERE COLUMN_NAME like '%'+@colums+'%' and TABLE_NAME in (SELECT distinct TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE') and TABLE_NAME <> @exTable 
		OPEN cursor_name -- 打开游标
		FETCH NEXT FROM cursor_name INTO  @tablename ,@columnname  -- 抓取下一行游标数据
		WHILE @@FETCH_STATUS = 0     --(-1 语句失败， -2 被提取行不存在）
		BEGIN
			SET @sql = 'update ' + @tablename + ' set ' + @columnname + ' =REPLACE('+@columnname+', '''+@OldId+''', '''+@NewId+''') where '+ @columnname + ' like '+'''%'+@OldId+'%'';' ;
			--print @sql 
			EXEC sp_executesql @sql
     	FETCH NEXT FROM cursor_name INTO @tablename,@columnname;
		END
		CLOSE cursor_name -- 关闭游标
		DEALLOCATE cursor_name -- 释放游标
    FETCH NEXT FROM cursor_Id INTO @OldId,  @NewId 
	END
CLOSE cursor_Id -- 关闭游标
DEALLOCATE cursor_Id -- 释放游标
--SELECT @returnVal
END