如何在select into语句中使用变量作为表名?

时间:2016-03-14 11:03:58

标签: sql-server tsql

我将表名作为变量处理时遇到问题,因为我需要每月自动将结果放到不同的表中(不使用任何高级过程来使此查询动态化)。有人可以帮我修改这段代码并使其有效吗?

declare @exp_dte as date;
set @exp_dte='2015-12-31';
print (@exp_dte);

declare @tab_mth as nvarchar(max);
set @tab_mth=year(@exp_dte)*100+month(@exp_dte);
print (@tab_mth);

declare @tab_name as nvarchar(max)
set @tab_name='mis_anl.dbo.BIK_' + @tab_mth
print (@tab_name);


IF OBJECT_ID (N'@tab_name', N'U') IS NOT NULL
begin
    drop table @tab_name
end

select distinct
*
into @tab_name
from table_x

2 个答案:

答案 0 :(得分:0)

使用动态sql,你不能将用户表名作为变量

declare @exp_dte as date;
set @exp_dte='2015-12-31';

declare @tab_mth as nvarchar(max);
set @tab_mth=year(@exp_dte)*100+month(@exp_dte);


declare @tab_name as nvarchar(max)
set @tab_name='mis_anl.dbo.BIK_' + @tab_mth


declare @sql1 nvarchar(max)
set @sql1='drop table '+@tab_name;

IF exists(select 1 from information_schema.tables where table_name=@tab_name)
begin
   exec(@sql1);
   end

declare @sql nvarchar(max)
set @sql='
select distinct
*
into '+@tab_name+'
from table_x'

exec (@sql)

答案 1 :(得分:0)

您必须使用动态SQL在运行时设置名称:

DECLARE @exp_dte  DATE    = '2015-12-31';
DECLARE @tab_name SYSNAME = '[dbo].' + QUOTENAME('BIK_' + FORMAT(@exp_dte, 'yyyyMM'));

IF OBJECT_ID (@tab_name, N'U') IS NOT NULL
BEGIN
   EXEC('DROP TABLE' +  @tab_name);
END

DECLARE @sql NVARCHAR(MAX) = N'SELECT DISTINCT *
                               INTO @tab_name
                               FROM table_x';

SET @sql = REPLACE(@sql, '@tab_name', @tab_name);

EXEC [dbo].[sp_executesql] @sql;

LiveDemo

说明:

  1. 尝试更加精诚
  2. 您可以使用FORMAT获取yyyyMM(SQL Server 2012 +)
  3. 始终QUOTENAME生成标识符以避免SQL注入攻击
  4. 我强烈建议您阅读 The Curse and Blessings of Dynamic SQL ,尤其是 CREATE TABLE @tbl