我有一张如下表。表名:TESTNUMBERS
ID(INT) NUMBER(INT) NAME(NVARCHAR(50))
1 1 Test
2 1 Test
3 2 Test2
当我插入 NUMBER 列时,如果不可用,我需要增加,如果可用,则最大 id 值 + 1 并确保该数字是否已作为参数传递,然后将其保存为原样。(这是为了确保行与NAME 也将具有相同的 NUMBER 列)。
我写了一个 SP,但有一些语法问题。
CREATE PROCEDURE TEST_STOREDPROC
@Name NVARCHAR(50),
@Number INT = 0,
@ID INT
AS
BEGIN
SET NOCOUNT ON
BEGIN TRY
DECLARE @IncrementID SMALLINT; SET @IncrementID=1;
DECLARE @IncrementNumber INT; SET @IncrementNumber = 1;
BEGIN TRAN
BEGIN
IF @Number = 0
BEGIN
SET @Number =
SELECT ISNULL(MAX(Number),0)+@IncrementNumber
from TESTNUMBERS
END
INSERT INTO TESTNUMBERS
([ID]
,[Name]
,[Number])
SELECT ISNULL(MAX([ID]),0)+@IncrementID as [ID]
,@Name
,@Number
FROM TESTNUMBERS
--return the ID of the column inserted
SELECT MAX([ID]) from TESTNUMBERS
END
COMMIT TRAN
END TRY
BEGIN CATCH
--TO DO
END CATCH
END
GO
我如何改进和纠正这个 SP?