我希望能够从表中提取自定义键值,但也希望它的性能像SQL Server插入时的IDENTITY(1,1)
列。
自定义键用于另一个应用程序,将需要由不同的功能使用,因此该值将需要从表中拉出并用于其他区域。
这里是我的尝试:
ALTER TRIGGER [sales].[trg_NextInvoiceDocNo]
ON [sales].[Invoice]
AFTER INSERT
AS
BEGIN
DECLARE @ResultVar VARCHAR(25)
DECLARE @Key VARCHAR(25)
EXEC [dbo].[usp_GetNextKeyCounterChar]
@tcForTbl = 'docNbr', @tcForGrp = 'docNbr', @NewKey = @ResultVar OUTPUT
UPDATE sales.InvoiceRET
SET DocNbr = @ResultVar
FROM sales.InvoiceRET
JOIN inserted ON inserted.id = sales.InvoiceRET.id;
END;
谢谢
您可以使用ROW_NUMBER()
,具体取决于要处理的并发类型。这是一些示例数据和一个可以在本地运行的演示。
-- Sample table
USE tempdb
GO
IF OBJECT_ID('dbo.sometable','U') IS NOT NULL DROP TABLE dbo.sometable;
GO
CREATE TABLE dbo.sometable
(
SomeId INT NULL,
Col1 INT NOT NULL
);
GO
-- Stored Proc to insert data
CREATE PROC dbo.InsertProc @output BIT AS
BEGIN -- Your proc starts here
INSERT dbo.sometable(Col1)
SELECT datasource.[value]
FROM (VALUES(CHECKSUM(NEWID())%100)) AS datasource([value]) -- simulating data from somewhere
CROSS APPLY (VALUES(1),(1),(1)) AS x(x);
WITH
id(MaxId) AS (SELECT ISNULL(MAX(t.SomeId),0) FROM dbo.sometable AS t),
xx AS
(
SELECT s.SomeId, RN = ROW_NUMBER() OVER (ORDER BY (SELECT NULL))+id.MaxId, s.Col1, id.MaxId
FROM id AS id
CROSS JOIN dbo.sometable AS s
WHERE s.SomeId IS NULL
)
UPDATE xx SET xx.SomeId = xx.RN;
IF @output = 1
SELECT t.* FROM dbo.sometable AS t;
END
GO
[每次运行:EXEC dbo.InsertProc 1;
,它会再返回3行,并带有正确的ID col。每次执行它时,它都会根据需要添加更多的行和自动递增。
SomeId Col1
-------- ------
1 62
2 73
3 -17