I have a table called Name_Tables
that contains the names of other tables.
Some of that tables have names like dbo.companyname.test
and others dbo.testtest
.
For all these tables, mentioned in the table Name_Tables
, I would like to delete the data, so that I have empty tables. I would like to do that by using dynamic SQL.
My code is executable and I can delete some records, but not all of them. Maybe you have an idea where my mistakes are...
DECLARE @i INT = 1
DECLARE @count INT = 50
DECLARE @tablename NVARCHAR(MAX)
DECLARE @sql NVARCHAR(MAX)
DECLARE @value NVARCHAR (MAX)`
WHILE(@i <= @count)
BEGIN
SET @tablename = (SELECT TOP (1) Expression FROM Name_Tables WHERE Id = @i);
IF EXISTS (SELECT '[dbo].[company$'+@tablename+']')
BEGIN
SET @sql = N'DELETE FROM [dbo].[company$'+@tablename+']';
EXECUTE sp_executesql @sql;
END
ELSE IF EXISTS (SELECT '[dbo].[' + @tablename+']')
BEGIN
SET @sql = N'DELETE FROM [dbo].[' + @tablename+']';
EXECUTE sp_executesql @sql;
END
ELSE
BEGIN
SET @i += 1;
END
SET @i += 1
END