sql-server - 如何使用存储过程创建临时表

标签 sql-server database

我想在 SQL Server 2012 中创建一个返回临时表的存储过程。

我的代码是

CREATE PROC [dbo].[aac_trial_balance_data]
    @company_code char(5),
    @target_level int,
    @StartDate char(12),
    @EndDate char(12)
AS
BEGIN
    SELECT
        dbo.getParentCode(chart_code,@target_level,LEVEL) chart_code,
        level,
        SUM(debit) debit, 
        SUM(credit) credit
    FROM
        acc_trial_balance_vw 
    WHERE
        convert(datetime, create_date, 103) between convert(datetime, cast(@StartDate as datetime), 103) 
                                                and convert(datetime, cast(@EndDate as datetime) + '23:59:59', 103)  
        AND company_code = @company_code 
    GROUP BY 
        chart_code, LEVEL 
END

我想在像这样的查询之后创建一个临时表

CREATE PROC [dbo].[aac_trial_balance_data]
    @company_code char(5),
    @target_level int,
    @StartDate char(12),
    @EndDate char(12)
AS
BEGIN
    (select 
            dbo.getParentCode(chart_code,@target_level,LEVEL) chart_code,
            level,
            SUM(debit) debit, 
            SUM(credit) credit
        from acc_trial_balance_vw 
        where 
        convert(datetime,create_date,103) between convert(datetime, cast(@StartDate as datetime) , 103) 
        and  convert(datetime, cast(@EndDate as datetime)+'23:59:59' , 103)  
        and company_code = @company_code 
         GROUP BY chart_code, LEVEL 
         )
         AS
         #TEMP-TABLE -- This is my Temp Table That i want to create
END

id怎么做到的

最佳答案

你可以创建临时表,只需使用

If Object_Id('Tempdb..#temp') Is Not Null
Drop Table #temp1
create table #temp(your columns)

Insert into #temp select...

或者使用 select into #temp like

select 
        dbo.getParentCode(chart_code,@target_level,LEVEL) chart_code,
        level,
        SUM(debit) debit, 
        SUM(credit) credit into #tempTable
    from acc_trial_balance_vw 
    where 
    convert(datetime,create_date,103) between convert(datetime, cast(@StartDate as datetime) , 103) 
    and  convert(datetime, cast(@EndDate as datetime)+'23:59:59' , 103)  
    and company_code = @company_code 
     GROUP BY chart_code, LEVEL 

关于sql-server - 如何使用存储过程创建临时表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42687538/

相关文章:

sql-server - 同时触发的 SSRS 报告订阅是否同时运行?

database - 如何确认记录的值是否符合 dolphindb 中的分区方案?

sql - 如何将记录从互连表复制到不同数据库中的另一个表?

sql-server - 使用 SELECT 语句分配变量

php - 如何使用 DATE_FORMAT() 对表格日期进行排序?

database - 是否可以通过 R(RMySQL) 向数据库表添加索引

sql - sqlite更新上的“没有这样的功能”错误

mysql - 将旧文本数据库转换为 SQL

mysql - 如何使用 odbc for filemaker 将数据从 filemaker pro 移动到 microsoft sql server studio

c# - 批量插入,asp.net