sql存储过程,选择进入

时间:2018-03-22 07:13:08

标签: sql-server tsql stored-procedures select-into

我尝试构建一个将数据插入表的存储过程, 运行后,表格为空。

这是代码:

CREATE TABLE invoices
(invoiceNo int,
 invoiceDate date,
 invoiceTotal int,
 invoiceType char(1))


alter PROCEDURE Invoices_AGG
@year int

AS
    select
    (case when MONTH(invoiceDate) >9 then concat('01','/',MONTH(invoiceDate),'/',year(invoiceDate)) else concat('01','/0',MONTH(invoiceDate),'/',year(invoiceDate)) end) as DateID,
    SUM(case when invoiceType = 'B' then invoiceTotal else 0 end) as Total_Incomes_TypeB,
    SUM(case when invoiceType = 'I' then invoiceTotal else 0 end) as Total_Incomes_TypeI
    into FACT_Invoices_AGG 
    from invoices
    where year(invoiceDate)=@year
    group by (case when MONTH(invoiceDate) >9 then concat('01','/',MONTH(invoiceDate),'/',year(invoiceDate)) else concat('01','/0',MONTH(invoiceDate),'/',year(invoiceDate)) end);


exec Invoices_AGG 2013

谢谢

2 个答案:

答案 0 :(得分:0)

您尚未指定要插入数据的表格,因为您的表格为空,您正在应用您的选择查询,因此它不会返回任何结果。 如果你想使用

into

您还应该提及FACT_Invoices_AGG功能的代码。

答案 1 :(得分:0)

SELECT INTO语句创建一个表并用数据填充它。执行2次或更多次该语句将失败(因为该表将在第一次运行时创建,并将尝试在第二次运行时再次创建它)。

如果表是空的,要么因为查询没有返回任何结果,要么因为我之前提到的原因而导致SP失败(甚至在构建结果时失败,例如转换错误)。使用SELECT INTO时,请务必先删除表IF EXISTS(如果这是您想要的)。

ALTER PROCEDURE Invoices_AGG
@year int

AS
BEGIN

    IF EXISTS( SELECT 'table exists' FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'FACT_Invoices_AGG'AND TABLE_SCHEMA = 'dbo')
        DROP TABLE dbo.FACT_Invoices_AGG

    select
        (case when MONTH(invoiceDate) >9 then concat('01','/',MONTH(invoiceDate),'/',year(invoiceDate)) else concat('01','/0',MONTH(invoiceDate),'/',year(invoiceDate)) end) as DateID,
        SUM(case when invoiceType = 'B' then invoiceTotal else 0 end) as Total_Incomes_TypeB,
        SUM(case when invoiceType = 'I' then invoiceTotal else 0 end) as Total_Incomes_TypeI
    into 
        FACT_Invoices_AGG 
    from 
        invoices
    where 
        year(invoiceDate)=@year
    group by 
        (case when MONTH(invoiceDate) >9 then concat('01','/',MONTH(invoiceDate),'/',year(invoiceDate)) else concat('01','/0',MONTH(invoiceDate),'/',year(invoiceDate)) end);

END
GO

另一种选择是更改SELECT INTO INSERT INTO (columnNames, ...) SELECT,这需要事先存在该表。

尝试在没有SELECT的情况下执行INTO,看看在计算结果时它是否失败。如果它没有,那么在使用SELECT INTO之前确保目标表不存在。