获取SQLServer中存储过程中列的最高值

时间:2011-06-17 16:49:24

标签: sql-server sql-server-2008 stored-procedures

我在SQL Server中有以下存储过程

IF OBJECT_ID ('kii.p_CreateSection') IS NOT NULL
   DROP PROCEDURE kii.p_CreateSection
GO

CREATE PROCEDURE kii.p_CreateSection
    @Name AS NVARCHAR(200),
    @DocumentId AS INT,
    @TypeId AS INT = NULL,
    @ReportId AS INT = NULL,
    @OrdinalPosition AS SMALLINT
AS
    INSERT INTO kii.Section (Name, DocumentId, TypeId, ReportId, OrdinalPosition)
    VALUES (@Name, @DocumentId, @TypeId, @ReportId, @OrdinalPosition)

    SELECT SCOPE_IDENTITY();
GO

GRANT EXECUTE on kii.p_CreateSection TO p_role_kii
GO

SectionDocument相关。每个文档都有几个部分,它们按OrdinalPosistion值排序。

我想测试一下,如果@OrdinalPosition的给定值为0,则将其设置为此文档+1的所有部分的最大值。

1 个答案:

答案 0 :(得分:1)

Insert kii.Section( Name, DocumentId, TypeId, ReportId, OrdinalPosition )
Select @Name, @DocumentId, @TypeId, @ReportId
    , Case
        When @OrdinalPosition <> 0 Then @OrdinalPosition
        Else    (
                Select Max( OrdinalPosition ) + 1
                From kii.Section
                Where DocumentId = @DocumentId
                )
        End