IF OBJECT_ID (N'[dbo].ReplaceCharsInCompanyName') IS NOT NULL
DROP FUNCTION [dbo].ReplaceCharsInCompanyName;
GO
CREATE FUNCTION [dbo].ReplaceCharsInCompanyName(@CharsToReplace VARCHAR(MAX), @ReplaceWith CHAR(1), @ReplaceIn VARCHAR(30))
RETURNS VARCHAR(30)
AS
BEGIN
DECLARE @i INT
SET @i = 0
WHILE @i < LEN(@CharsToReplace)
BEGIN
SELECT @i = @i + 1
SET @ReplaceIn = REPLACE(@ReplaceIn, SUBSTRING(@CharsToReplace, @i, 1), @ReplaceWith)
END
RETURN @ReplaceIn
END
GO
DECLARE @OldDatabaseName VARCHAR(128), @NewDatabaseName VARCHAR(128)
SELECT @OldDatabaseName = '',
@NewDatabaseName = ''
DECLARE @CompaniesQuery VARCHAR(200),
@Query VARCHAR(MAX),
@BlankChar VARCHAR(10)
SET @CompaniesQuery = 'SELECT [Name] FROM [' + @NewDatabaseName + '].[dbo].[Company]'
DECLARE @CompaniesFormatted TABLE(CompanyName VARCHAR(30))
INSERT INTO @CompaniesFormatted EXEC (@CompaniesQuery)
DECLARE CompaniesCurser CURSOR FOR SELECT CompanyName from @CompaniesFormatted
DECLARE @CompanyName VARCHAR(MAX)
OPEN CompaniesCurser
FETCH CompaniesCurser INTO @CompanyName
WHILE @@FETCH_STATUS != -1
BEGIN
SELECT @CompanyName = [dbo].ReplaceCharsInCompanyName('."\/''%][', '_', @CompanyName)
PRINT @CompanyName
SET @Query =
'INSERT INTO [' + @NewDatabaseName + '].[dbo].[' + @CompanyName + '${NAV TABLE NAME}] ({Table fields})
SELECT {Table fields}
FROM [' + @OldDatabaseName + '].[dbo].[' + @CompanyName + '${NAV TABLE NAME}]';
EXEC (@Query)
FETCH CompaniesCurser INTO @CompanyName
END
CLOSE CompaniesCurser
DEALLOCATE CompaniesCurser
GO
IF OBJECT_ID (N'[dbo].ReplaceCharsInCompanyName') IS NOT NULL
DROP FUNCTION [dbo].ReplaceCharsInCompanyName;