更改临时表以声明它们

时间:2015-12-17 17:57:27

标签: sql sql-server

关于临时表和声明表的问题。如果我更改临时表' ChangedData'和' PackageDatatoProcess'他们自己的变量' @ ChangedData'和' @ PackageDatatoProcess',我可以问我如何更改select into语句,因为我之前没有完成此操作。实际上我告诉我们可以声明表而不是使用select into,但只需要一些帮助:

select distinct * into #PackageDataToProcess from #ChangedData pp
        outer apply (
            select pk.Reference, pjl.PackageToJournalLinkId, j.CreatedDate, pccl.PackageCostChangeLogId from Jet2Holidays.dbo.Package pk
            inner join Jet2Holidays.dbo.PackageToJournalLink pjl on pk.PackageId = pjl.PackageId
            inner join Jet2Holidays.dbo.Journal j on pjl.JournalId = j.JournalId
                and j.PrincipalName= iif(@AllowNonSupportChanges = 0, 'HolidaysSupport', j.PrincipalName) 
            inner join Jet2Holidays.dbo.BusinessProcess bp on pjl.BusinessProcessId = bp.BusinessProcessId
                and bp.[Description] =  iif(@AllowNonSupportChanges = 0, 'CallCentreAction', bp.[Description]) 
            left outer join Jet2Holidays.dbo.PackageCostChangeLog pccl on pccl.PackageToJournalLinkId = pjl.PackageToJournalLinkId
            where pk.Reference = pp.PackageReference
            and pp.JournalID = pjl.JournalId

            ) as packageData

1 个答案:

答案 0 :(得分:2)

首先,您声明变量表如下:

DECLARE @PackageDataToProcess TABLE
(
    Reference UNIQUEIDENTIFIER
,   PackageToJournalLinkId INT
,   CreatedDate DATETIME
,   PackageCostChangeLogId INT
,   {other columns here}
)

DECLARE @ChangedData TABLE
(
    Reference UNIQUEIDENTIFIER
,   PackageToJournalLinkId INT
,   CreatedDate DATETIME
,   PackageCostChangeLogId INT
,   {other columns here}
)

此时您可以像这样填充@ChangedData表:

INSERT @ChangedData ( Reference, PackageToJournalLinkId, CreatedDate, PackageCostChangeLogId, {other columns})
SELECT Reference, PackageToJournalLinkId, CreatedDate, PackageCostChangeLogId, {other columns} 
   FROM ChangedDataSource -- Table, Procedure, Function

然后您可以通过将@PackageDataToProcess替换为#PackageDataToProcess来运行您的代码。在这里再次略微重写(来自原文):

    INSERT @PackageDataToProcess
    select distinct pp.* from @ChangedData pp
    outer apply (
        select pk.Reference, pjl.PackageToJournalLinkId, j.CreatedDate, pccl.PackageCostChangeLogId from Jet2Holidays.dbo.Package pk
        inner join Jet2Holidays.dbo.PackageToJournalLink pjl on pk.PackageId = pjl.PackageId
        inner join Jet2Holidays.dbo.Journal j on pjl.JournalId = j.JournalId
            and j.PrincipalName= iif(@AllowNonSupportChanges = 0, 'HolidaysSupport', j.PrincipalName) 
        inner join Jet2Holidays.dbo.BusinessProcess bp on pjl.BusinessProcessId = bp.BusinessProcessId
            and bp.[Description] =  iif(@AllowNonSupportChanges = 0, 'CallCentreAction', bp.[Description]) 
        left outer join Jet2Holidays.dbo.PackageCostChangeLog pccl on pccl.PackageToJournalLinkId = pjl.PackageToJournalLinkId
        where pk.Reference = pp.PackageReference
        and pp.JournalID = pjl.JournalId

        ) as packageData

您声明的tabled将以与非全局临时表的方式类似的方式超出范围。