﻿--[dbo].[CopyObjectFromSchema]  'C6Mart', 'tt4', 'RP_'
CREATE procedure [dbo].[CopyObjectFromSchema] 
@FromSchemaName NVARCHAR(50),
@ToSchemaName NVARCHAR(50),
@LikeName NVARCHAR(MAX)
AS
Begin
DECLARE @ObjCopyName VARCHAR(MAX);
DECLARE @ObjContent nvarchar(MAX);
DECLARE @ObjIDSchemaTo INT
if (@FromSchemaName is null Or @FromSchemaName = '' Or 
    @ToSchemaName is null Or @ToSchemaName = '')
begin
   RAISERROR ('Valorizzare entrambi gli Schema Name!', -- Message text.
               16, -- Severity.
               1 -- State.
               );
   return
end
IF (NOT EXISTS (SELECT * FROM sys.schemas WHERE name = @ToSchemaName)) 
BEGIN
    EXEC ('CREATE SCHEMA ' + @ToSchemaName + ' AUTHORIZATION [dbo]')
END
SET @ObjIDSchemaTo = (SELECT SCHEMA_ID FROM sys.schemas WHERE name= @ToSchemaName)
DECLARE TABLECURSOR CURSOR FOR
SELECT [NAME] FROM sys.objects WHERE [TYPE] in (N'U') and schema_id = (SELECT SCHEMA_ID FROM sys.schemas WHERE name= @FromSchemaName)
AND [NAME] LIKE '%' + @LikeName + '%'
OPEN TABLECURSOR
FETCH NEXT FROM TABLECURSOR INTO @ObjCopyName
WHILE @@FETCH_STATUS = 0
BEGIN  --STORED PROC LOOP
     BEGIN TRY
     PRINT @ObjCopyName
     IF (EXISTS (SELECT * FROM sys.objects WHERE name = @ObjCopyName and schema_id = (SELECT SCHEMA_ID FROM sys.schemas WHERE name= @ToSchemaName))) 
        BEGIN
           execute dbo.DropObject @ObjCopyName, @ObjIDSchemaTo
        END
     Declare @statement nvarchar(max)
     Set @statement = 'SELECT * INTO ' + @ToSchemaName + '.' + @ObjCopyName + ' FROM ' + @FromSchemaName + '.' + @ObjCopyName + ' WHERE 1=2'
     print @statement
     execute sp_executeSQL @statement
     END TRY
     BEGIN CATCH
        SELECT  ERROR_MESSAGE()
     END CATCH
    FETCH NEXT FROM TABLECURSOR INTO @ObjCopyName
END 
CLOSE TABLECURSOR;
DEALLOCATE TABLECURSOR;
DECLARE PROCCURSOR CURSOR FOR
    SELECT NAME, REPLACE (OBJECT_DEFINITION(OBJECT_ID), @FromSchemaName, @ToSchemaName)
    FROM sys.objects WHERE [TYPE] in (N'P', N'PC', N'FN', N'V') and schema_id = (SELECT SCHEMA_ID FROM sys.schemas WHERE name= @FromSchemaName)
    AND NAME LIKE '%' + @LikeName + '%' ORDER BY [TYPE]
OPEN PROCCURSOR
FETCH NEXT FROM PROCCURSOR INTO @ObjCopyName, @ObjContent
WHILE @@FETCH_STATUS = 0
BEGIN  --STORED PROC LOOP
     BEGIN TRY
     PRINT @ObjCopyName
     PRINT @ObjContent
     IF (EXISTS (SELECT * FROM sys.objects WHERE name = @ObjCopyName and schema_id = (SELECT SCHEMA_ID FROM sys.schemas WHERE name= @ToSchemaName))) 
        BEGIN
           execute dbo.DropObject @ObjCopyName, @ObjIDSchemaTo
        END
     execute sp_executeSQL @statement = @ObjContent
     END TRY
     BEGIN CATCH
        SELECT  ERROR_MESSAGE(), @ObjCopyName, @ObjContent
     END CATCH
    FETCH NEXT FROM PROCCURSOR INTO @ObjCopyName, @ObjContent
END --STORED PROC LOOP
CLOSE PROCCURSOR;
DEALLOCATE PROCCURSOR;
END