Sql server 如何在select into语句中使用变量作为表名?
我在将表名视为变量时遇到了一个问题,因为我需要每月自动将结果放入不同的表中(而不使用任何高级过程使此查询成为动态的)。有人能帮我修改这个代码并使它工作吗Sql server 如何在select into语句中使用变量作为表名?,sql-server,tsql,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 @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
使用动态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)
必须使用动态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;
备注:
格式
获取yyyyym
(SQL Server 2012+)QUOTENAME
生成标识符以避免SQL注入攻击