Hi All,
i have a database that every time we get a new customer a new set of tables get added, I would like to know if it's possible to dynamically create a union so I have all the results are visible in one query currently, the way i achive it at the moment is using a loop and create a query per table but its all sperate queries rather than in one consolidated view
would anyone be able to advise or help me, i don't have access to create tables so I cannot insert into a table
DECLARE @Account As NVARCHAR(100), @TableID As NVARCHAR(100), @Output varchar(250) , @Mysql As NVARCHAR(Max), @dbname varchar(100)
Set @TableID = '$Item';
DECLARE db_cur cursor for
SELECT substring(name,1,charindex('$',name)-1)
FROM SYSOBJECTS
WHERE xtype = 'U' And name like CONCAT( '%' ,@TableID , '') Order by substring(name,1,charindex('$',name)-1)
open db_cur
fetch next from db_cur into @dbname
while @@FETCH_STATUS = 0
begin
Set @Output = @dbname + @TableID;
--run SQL
Set @MySql = '
SELECT
'''+@dbname+''' As AccountName,
Count(*)
FROM ' + CONCAT('[dbo].[' , @Output , ']' ) + '
'
EXEC sp_executesql @MySql
fetch next from db_cur into @dbname
end
close db_cur
deallocate db_cur