2016-06-22 60 views
0
SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 

ALTER PROCEDURE [dbo].[uspGetBillOfMaterials] 
    @StartProductID [int], 
    @CheckDate [datetime] 
AS 
BEGIN 
    SET NOCOUNT ON; 

    -- Use recursive query to generate a multi-level Bill of Material (i.e. all level 1 
    -- components of a level 0 assembly, all level 2 components of a level 1 assembly) 
    -- The CheckDate eliminates any components that are no longer used in the product on this date. 
    WITH [BOM_cte]([ProductAssemblyID], [ComponentID], [ComponentDesc], [PerAssemblyQty], [StandardCost], [ListPrice], [BOMLevel], [RecursionLevel]) -- CTE name and columns 
    AS (
     SELECT b.[ProductAssemblyID], b.[ComponentID], p.[Name], b.[PerAssemblyQty], p.[StandardCost], p.[ListPrice], b.[BOMLevel], 0 -- Get the initial list of components for the bike assembly 
     FROM [Production].[BillOfMaterials] b 
      INNER JOIN [Production].[Product] p 
      ON b.[ComponentID] = p.[ProductID] 
     WHERE b.[ProductAssemblyID] = @StartProductID 
      AND @CheckDate >= b.[StartDate] 
      AND @CheckDate <= ISNULL(b.[EndDate], @CheckDate) 
     UNION ALL 
     SELECT b.[ProductAssemblyID], b.[ComponentID], p.[Name], b.[PerAssemblyQty], p.[StandardCost], p.[ListPrice], b.[BOMLevel], [RecursionLevel] + 1 -- Join recursive member to anchor 
     FROM [BOM_cte] cte 
      INNER JOIN [Production].[BillOfMaterials] b 
      ON b.[ProductAssemblyID] = cte.[ComponentID] 
      INNER JOIN [Production].[Product] p 
      ON b.[ComponentID] = p.[ProductID] 
     WHERE @CheckDate >= b.[StartDate] 
      AND @CheckDate <= ISNULL(b.[EndDate], @CheckDate) 
     ) 
    -- Outer select from the CTE 
    SELECT 
     b.[ProductAssemblyID], b.[ComponentID], b.[ComponentDesc], 
     SUM(b.[PerAssemblyQty]) AS [TotalQuantity], b.[StandardCost], 
     b.[ListPrice], b.[BOMLevel], b.[RecursionLevel] 
    FROM 
     [BOM_cte] b 
    GROUP BY 
     b.[ComponentID], b.[ComponentDesc], b.[ProductAssemblyID], 
     b.[BOMLevel], b.[RecursionLevel], b.[StandardCost], b.[ListPrice] 
    ORDER BY 
     b.[BOMLevel], b.[ProductAssemblyID], b.[ComponentID] 
    OPTION (MAXRECURSION 25) 
END; 

有沒有辦法讓我可以獲取SQL Server存儲過程中使用的所有列名?我需要在條款如選擇,所使用的列名其中,按組,按順序等我需要從SQL Server存儲過程中獲取列名

在此先感謝

+0

'FMTONLY' https://msdn.microsoft.com/en-US/library/ms173839.aspx –

+0

@IvanStarostin - 相關提示 –

+0

@IvanStarostin - 但它不會幫助OP。這會使列僅出現在「SELECT」列表中。 OP希望在'where,group by,order by等中使用列' –

回答

0

我不覺得有什麼,可以給你準確的所有任何查詢存儲過程中使用的列。有一種方法可以使用SSMS來完成。

  • 轉至對象資源管理器>數據庫> YourDatabase>可編程>存儲過程
  • 右鍵點擊YourProcedure>視圖依賴性
  • 選擇單選按鈕列表中第二個選項(對象上[YourProcedure]取決於

您將獲得所有表格,表格鏈接和列的過程依賴的樹視圖。

讓我知道這是否是什麼你自找的。

+0

謝謝,但我需要列名稱,上面的方式沒有帶我到任何地方。 –

+0

你確定你嘗試過嗎?這種方式確實可以爲您提供SQL存儲過程所依賴的列的名稱。 –

+0

我也試過這個存儲過程,做了一個簡單的「從dbo.MyTable中選擇A,B,C」,並且只有「MyTable」出現了,而不是A,B,C。 – granadaCoder

相關問題