我有这个SQL查询:
delete from Main.dbo.ACTIVITY;
insert into Main.dbo.ACTIVITY
select * from MainTemp.dbo.ACTIVITY;
我希望在执行ACTIVITY
之后为10个表执行该SQL。
有没有办法做到这一点?定义一个变量还是什么?
我在SQL Server Management Studio 10(= SQL Server 2008)
中运行查询答案 0 :(得分:6)
在这种情况下编写动态查询。以下示例可能会给您一些想法
e.g。
Declare @tableNames table(Id int identity,TableNames Varchar(10))
Insert Into @tableNames Values('Table1'),('Table2'),('Table3'),('Table4')
Declare @query AS Varchar(max)
Declare @tblNames AS Varchar(max)
Declare @count AS int
Declare @i AS int = 1
Select @count = Count(*) from @tableNames
While(@i <=@count)
Begin
Select @tblNames = TableNames from @tableNames Where Id = @i
Set @query = 'delete from ' + @tblNames
Set @query += '; insert into ' + @tblNames
Set @query += '; select * from ' + @tblNames
print @query --exec @query
Set @i += 1
End
答案 1 :(得分:4)
declare @tablename sysname = N'ACTIVITY';
declare @sql nvarchar(max);
set @sql = N'delete from Main.dbo.' + quotename(@tablename);
exec sp_executesql @sql;
set @sql = N'insert into Main.dbo.' + quotename(@tablename);
exec sp_executesql @sql;
set @sql = N'select * from Main.dbo.' + quotename(@tablename);
exec sp_executesql @sql;
由于SQL注入风险,在处理动态SQL时使用QUOTENAME非常重要非常重要。动态SQL有利有弊,对于部门讨论,请参阅The Curse and Blessings of Dynamic SQL。
SSMS和SQLCMD具有使用客户端变量替换的功能:
:setvar tablename Main.dbo.ACTIVITY
delete from $(tablename);
insert into $(tablename);
select * from $(tablename);
SQLCMD模式变量闪耀的地方是批量使用,因为变量可以通过-v argument传递。例如:
c:\>for /f %i in (tablenames.txt) do sqlcmd -S <servername> -E -d <dbname> -v tablename=%i -Q "truncate table $(tablename)"
请注意,在SSMS中,必须明确启用SQLCMD执行模式。