I'm currently writing a stored procedure which shall be executed on database A. It loops over other databases and shall create a view there if it can not find it. Here's a snippet:
BEGIN
IF OBJECT_ID('['+ @source_db+'].['+@source_schema+'].['+@current_table+']', 'V') IS NULL
BEGIN
print('source view not available for ' + @source_db )
print('creating view')
EXEC('USE ['+@source_db+']; create view ['+@source_schema+'].['+@current_table+'] as select * from [XYZ].[' + @dc_guid + '].[' + @current_table+']' )
print('view created')
END
END
But the EXEC statement obviously not works, since the View Statement must be the first one of a batch. But separating the use command to another EXEC statement doesn't work either (I found out that both EXEC statements are completely separate from another). As far as I know (and also tried out) it is not possible to use the "Go" command within EXEC.
What else can I do to achieve this?