I have this SQL query:
delete from Main.dbo.ACTIVITY;
insert into Main.dbo.ACTIVITY
select * from MainTemp.dbo.ACTIVITY;
and I want to execute that SQL for 10 tables after executing for ACTIVITY.
Is there any way to do that? Defining a variable or something?
I’m running the query in SQL Server Management Studio 10 (= SQL Server 2008)
Use dynamic SQL
It is very important to use the QUOTENAME when handling dynamic SQL because of the SQL injection risk. Dynamic SQL has pros and cons, for an in dept discussion see The Curse and Blessings of Dynamic SQL.
Use SQLCMD execution mode
SSMS and SQLCMD have capabilities to use client side variable substitution:
Where SQLCMD mode variables shine is when used in batches because the variables can be passed in via the -v argument. For example:
Note that in SSMS the SQLCMD execution mode must be enabled explicitly.