Skip to main content

Check if table contains data per company

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 @DatabaseName VARCHAR(128), @TableName VARCHAR(128)
-------------------------------PRE STEP-------------------------------
SELECT @DatabaseName = '',
@TableName = ''
-------------------------------DO NOT EDIT UNDER THIS LINE-------------------------------

DECLARE @CompaniesQuery VARCHAR(200),
@Query VARCHAR(MAX),
@BlankChar VARCHAR(10)

SET @CompaniesQuery = 'SELECT [Name] FROM [' + @DatabaseName + '].[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 =
'SELECT * FROM [' + @DatabaseName + '].[dbo].[' + @CompanyName + '$' + @TableName + ']';

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;