实现将存储过程作为inser into的数据源,插入临时表

来源:互联网 发布:激战2女夏尔捏脸数据 编辑:程序博客网 时间:2024/05/29 04:48

1、引言

        今天项目制作报表需要实现一个功能,将执行一个存储过程后的数据表,作为数据源,插入到一张临时表里。由于这个临时表知识系统自动生成的字符串,并没有在数据库(SQL Server)定义,所以,做出各种尝试,均告失败。


2、两种T-SQL语法

     1、select...into...from

     2、insert into ... select

      第一次接触select...into...from...和insert into...select...有很多人都会误解, 从表面上看都是把相关信息查询出来,然后添加到一个表里,其实还远远没有这么简单。

    insert into select语句:其语法形式为:Insert into Table2(field1,field2,...) select value1,value2,... from Table1

    select into from 语句:该语法形式为:select vale1, value2 into Table2 from Table1

    区别:insert into select语句,这里的要求就是Table2必须已经存在,如果不存在,系统则会提示对象无效,而select into from语句,这里要求的是MyTable1不存在,因为在插入的时候,系统会自动创建MyTable1,如果之前MyTable1已经被创建,系统就会提示已经存在表。


3、解决方案

      上面为什么要讲两种T-SQL语法呢,正是因为我想要模仿上述语句,将一个存储过程,替换select语句查询出来的表,来进行实现,结果发现,无论是insert into select 还是 select into from,均无法实现需求。

      例如:select * into abc exec getcltpossales_sp '','','','',''

      PS:getcltpossales_sp是系统中存在的一个存储过程,执行出来的结果是一张表。

      错误信息:Msg 263, Level 16, State 1, Line 1
      必须指定要从中选择的表。
      Msg 1038, Level 15, State 5, Line 1
      缺少对象或列名,或者对象或列名为空。对于 SELECT INTO 语句,请确保每列均具有名称。对于其他语句,请查找空的别名。不允许使用定义为 "" 或 [] 的别名。请将别名更改为有效名称。

      解决:

        在存储过程多定义一个传入参数@TempTableName varchar(50) ,为临时表名,在存储过程做查询的时候用select into from 方法,最后执行。中间具体实现就不给出了。

create proc [dbo].[getsizepossales_sp]                       
(        
@REGIONcode varchar(50),
@hzcode   varchar(50),                          
@dkhflag varchar(50),              
@beginyear varchar(10),   
@endyear varchar(10)  ,
@TempTableName varchar(50)     
)        

set @SQL= '
select keyid,period,state,year,xsdigit,tbrate,hbrate,ljtbrate,ljhbrate

,case when [month]=1 then sum(xsdigit) end Jan

,case when [month]=2 then sum(xsdigit) end Feb

,case when [month]=3 then sum(xsdigit) end Mar

,case when [month]=4 then sum(xsdigit) end Apr

,case when [month]=5 then sum(xsdigit) end May

,case when [month]=6 then sum(xsdigit) end Jun

,case when [month]=7 then sum(xsdigit) end Jul

,case when [month]=8 then sum(xsdigit) end Aug

,case when [month]=9 then sum(xsdigit) end Sep

,case when [month]=10 then sum(xsdigit) end Oct

,case when [month]=11 then sum(xsdigit) end Nov

,case when [month]=12 then sum(xsdigit) end Dec

 into '+@TempTableName+' from #Retable group by keyid,period,[month] ,state,year,xsdigit,tbrate,hbrate,ljtbrate,ljhbrate '                    
 
 --select @SQL
 EXEC(@SQL)














0 0
原创粉丝点击