如何在sql中定义变量而不是表名?

时间:2012-11-14 07:45:48

标签: sql sql-server

我有这个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)

中运行查询

2 个答案:

答案 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)

使用动态SQL

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

使用SQLCMD execution mode

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执行模式。