Вам необходимо включить вставку в сборку @sql, например,
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.Alltableunion'))
begin
drop table alltableunion
end
go
--create table alltableunion(query varchar(max),view_name varchar(max))
--go
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.AllRecords'))
begin
drop table allrecords
end
go
DECLARE @Sql NVARCHAR(MAX);
DECLARE @view_name NVARCHAR(MAX);
--Drop TABLE IF EXISTS AllTableUnion
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.AllRecords') AND type in (N'U'))
BEGIN
CREATE table dbo.AllRecords
(
query varchar(MAX),
view_name varchar(MAX)
)
END
SELECT 'insert into allrecords(query,view_name)
select count(*),'+char(39)+'[' + SCHEMA_NAME(t.schema_id) + '].[' + t.name + ']' + char(39) +
' from ' + '[' + SCHEMA_NAME(t.schema_id) + '].[' + t.name + ']' as query,
'[' + SCHEMA_NAME(t.schema_id) + '].[' + t.name + ']' as view_name
into AllTableUnion
FROM sys.all_objects AS t
where t.schema_id=1 and t.TYPE like 'V'
group by t.schema_id, t.name
DECLARE Cur CURSOR LOCAL FAST_FORWARD FOR
SELECT query,view_name FROM AllTableUnion --<-- table where sql is stored
OPEN Cur
FETCH NEXT FROM Cur INTO @Sql, @view_name
WHILE (@@FETCH_STATUS = 0)
BEGIN
print @sql
exec sp_executesql @sql
FETCH NEXT FROM Cur INTO @Sql , @view_name
END
CLOSE Cur
DEALLOCATE Cur;
select * from allrecords
query view_name
----------- ---------
5 [dbo].[vu]
(1 row(s) affected)
А почему бы вам установить счетчик varchar (max)?