'Use sp_MSforeachtable for creating table backups dynamicaly
I'm trying to use sp_MSforeachtable to create backup tables dynamically using this query.
exec sp_MSforeachtable
@command1='Print ''[?_bckp]''',
@command2='select * into ''[?_bckp_2022]'''' from ?;'
@whereand=' and o.Name in (
''<table list>''
)
and schema_name(schema_id) = ''dbo'''
I'm getting an error for @whereand but I think it is a bogus error. I think the problem is in the command2 at [?_bckp_2022]. The table name is coming out of command1 is looking like [[dbo]].[table_name]]_bckp]. I think the sql command generated in command2 is causing the error at the execution stage. My questions are:
- What am I doing wrong?
- How can I remove schema out of the table-generated name in command2?
Thanks
Solution 1:[1]
There was a comma missing. Thank everyone.
Solution 2:[2]
As stated in the comments, it is much easier to do it using sys.tables.
Use string_agg to concatenate the dynamic command and exec() to execute it
declare @sql nvarchar(max);
select @sql = string_agg ('select * into ' + quotename(name + '_bckp_2002') + ' from ' + quotename(name), ';' + char(13))
from sys.tables t
print @sql
exec (@sql)
You can filter the required tables easily in the WHERE clause
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | LeoG |
| Solution 2 | Squirrel |
