T-SQL 存储过程 Join Table Value Parameter Twice

T-SQL Stored Procedure Join Table Valued Parameter Twice

我有一个 table 值的参数我想加入,不只是一次,而是两次。一次获取一行,第二次获取父行

我几乎可以肯定这可以用普通的 tables 完成。可以用 table 值参数来完成吗?

USE [ActivityStore_220.0_Model]
GO
/****** Object:  StoredProcedure [dbo].[SnapshotLineItemAggregations]    Script Date: 3/24/2017 5:49:43 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[SnapshotLineItemAggregations]    
    @billingCycleIteration int,
    @tableOfBusinessEntities [dbo].[BusinessEntityNode] READONLY,
    @tableOfActivityNames [dbo].[IdNamePair] READONLY
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    BEGIN TRANSACTION

    --Note this will ONLY delete items that have the exact same BillingCycleIterationId.
    --This will not delete old records from previous billing cycle iterations.  
    DELETE FROM [dbo].[LineItemAggregationSnapshot] WHERE 
    BillingCycleIterationId = @billingCycleIteration

    -- Insert statements for procedure here
    INSERT INTO [dbo].[LineItemAggregationSnapshot]
    SELECT [BillingCycleIterationId]
      ,[BillToAccountId]      
      ,CASE be_table.BusinessEntityTypeId WHEN 1 THEN 'Merchant' ELSE 'Organization' END AS [BusinessEntityType]
      ,[BusinessEntityId]
      ,[ProductId]
      ,[ActivityId]
      ,[RateProfileId]
      ,[Count]
      ,[Quantity]
      ,[ConversionRate]
      ,[OriginatingCurrency]
      ,[ConvertedQuantity]
      ,[QuantityUnits]
      ,[Rate]
      ,be_table.Name [BusinessEntityDescription]
      ,parent_be.Name [ParentBusinessEntityName]      
      ,activity_table.Name [ItemDescription]
      ,[LineItemData]
    FROM [dbo].[LineItemAggregation] lia
    LEFT OUTER JOIN @tableOfBusinessEntities be_table
    ON be_table.Id = lia.BusinessEntityId
    LEFT OUTER JOIN @tableOfActivityNames activity_table
    ON activity_table.Id = lia.ActivityId
    LEFT OUTER JOIN @tableOfBusinessEntities parent_be --the second join
    ON parent_be.Id = be_table.ParentId
    WHERE BillingCycleIterationId = @billingCycleIteration

    COMMIT TRANSACTION
    select * from LineItemAggregationSnapshot
    where BillingCycleIterationId = @billingCycleIteration
END

当我只加入一次@tableOfBusinessEntities 时,我对这个存储过程没有任何问题。但是我第二次尝试加入 table 值参数时,存储过程似乎不再起作用。

我没有收到错误,我尝试连接的每一列都显示为空,就好像连接行不再匹配一样。

所以,错误出在我的代码中的其他地方。我是如何填充 .NET 数据表的,或者更确切地说,我是如何填充的。

一旦该问题得到解决,存储过程就会发挥作用。

所以对于未来想知道的人来说,答案是肯定的,您可以多次加入 table 值参数,就像在 SQL 服务器中加入普通 table 一样。