简体   繁体   中英

How can I generate a sequence number in a empty table

I am trying to make a query that can generate the latest sequence number +1 to the new record in sql server.

let ignore the insert part first, I write a query like this:

SELECT 'asdf' AS col1, CASE WHEN EXISTS (SELECT pk_sales_inv_no FROM salesInvoice WHERE pk_sales_inv_no LIKE 'Q-ARF2206-%') THEN 1 ELSE 0 END AS EXPR1

It looks fine, when the record with same prefix exists, It return 1, else 0. 在此处输入图像描述

Because I have to process the current latest sequence number in the true value part, so I change my query with this to get the pk_sales_inv_no for the true part processing.

SELECT TOP (1) 'asdf' AS col1, CASE WHEN EXISTS (SELECT pk_sales_inv_no FROM salesInvoice WHERE pk_sales_inv_no LIKE 'Q-ARF2206-%') THEN 1 ELSE 0 END AS EXPR1 FROM salesInvoice WHERE (pk_sales_inv_no LIKE 'Q-ARF2206-%') ORDER BY pk_sales_inv_no DESC

Then problem happens, because the select result is totally empty, so It doesn't return the 1 or 0.

How can I improve it to work out with a empty select result.

You can write a simple scalar udf, if you need it in JOIN adapt it as a table value function.

I doubt that this is what you need, I think you want to get the number after the 2nd dash



IF OBJECT_ID (N'dbo.udf_lastSequence') IS NOT NULL
   DROP FUNCTION dbo.udf_lastSequence
GO

CREATE FUNCTION dbo.udf_lastSequence (@invNo varchar(100))
RETURNS int
AS
BEGIN
    DECLARE @lastInvNo VARCHAR(100)
    DECLARE @search VARCHAR(100)
    DECLARE @result int

    SET @result = 0
    SET @search = CONCAT(@invNo, '%');

    SELECT TOP 1 @lastInvNo = pk_sales_inv_no
    FROM salesInvoice 
    WHERE (pk_sales_inv_no LIKE @search)
    ORDER BY pk_sales_inv_no DESC

    IF @lastInvNo IS NOT NULL
        SET @result = CAST(REPLACE(@lastInvNo, @invNo, '') AS INT); 

    return @result
END
GO

Try it with SELECT dbo.udf_lastSequence('Q-ARF2206-') WITHOUT the final % charter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM