How to set a calculated column using a subquery

前端 未结 2 501
旧巷少年郎
旧巷少年郎 2021-01-17 05:43

I have a table to which I would like to add a calculated column. The query I want to set it to is more complex than a standard arithmetic operation and I am unsure how to se

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-17 06:08

    It is possible to add subquery with a little trick (UDF), see my example ([ChildCount] field):

    CREATE TABLE [wp].[StorageData](
        [ID] [int] IDENTITY(1,1) NOT NULL,
        [Name] [nvarchar](200) NOT NULL,
        [StorageHid] [hierarchyid] NOT NULL,
        [StoragePath]  AS ([StorageHid].[ToString]()),
        [StorageLevel]  AS ([StorageHid].[GetLevel]()),
        [StorageParentHid]  AS ([StorageHid].[GetAncestor]((1))),
        [StorageParent]  AS ([StorageHid].[GetAncestor]((1)).ToString()),
        [ChildCount]  AS ([wp].[GetStorageDataChildItemCount]([StorageHid].[ToString]()))
    )
    
    CREATE FUNCTION [wp].[GetStorageDataChildItemCount]
    (
        @storagePath NVARCHAR(4000)
    )
    RETURNS INT
    AS
    BEGIN
    
        DECLARE @ret INT = 0;
        SET @ret = (SELECT COUNT(ID) FROM [wp].[StorageData] R WHERE R.StorageParent = @storagePath)
        RETURN @ret;
    
    END
    

提交回复
热议问题