﻿

--单位补充英文名称
IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Base_Unit' AND COLUMN_NAME = 'UnitEnName')
BEGIN
	ALTER TABLE Base_Unit ADD UnitEnName nvarchar(200);
END
GO

--替换数据表
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'DataIdMove') AND type = N'U')
BEGIN
CREATE TABLE [dbo].[DataIdMove](
	[OldId] [nvarchar](50) NOT NULL,
	[NewIds] [nvarchar](50) NULL,
	[ColumType] [nvarchar](50) NULL,
 CONSTRAINT [PK_DataIdMove] PRIMARY KEY CLUSTERED 
(
	[OldId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'OldId' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'DataIdMove', @level2type=N'COLUMN',@level2name=N'OldId'
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'NewIds' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'DataIdMove', @level2type=N'COLUMN',@level2name=N'NewIds'
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'ColumType' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'DataIdMove', @level2type=N'COLUMN',@level2name=N'ColumType'
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'替换数据表' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'DataIdMove'
END

GO






CREATE PROC [dbo].[SP_DataIdMove]
		@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 not like 'View_%' 
		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



GO


