Sequential Increment in Alphanumeric Invoice Number using MSSQL - c#

i have a table named as sales. In this table i have a column Invoice_Number. What i want to achieve is to get invoice number in alphanumeric sequential order i.e. one Static Letter and then a number that changes just like A1,A2,A3... and so on. i don't want to change A to B as i saw in rest of the examples.
I can get the numeric increment by this query:
Select IsNull(MAX([Invoice_Number] + 1), 1) from sales
But it cannot add an alphabet prior to it.
Thanks.

Try using a cast like so to return a varchar, let me know if this helps :).
SELECT 'A' + CAST(ISNULL(MAX([Invoice_Number] + 1), 1) AS nvarchar) FROM sales

You could use your existing identity column as a seed. Combine this with a computed column to return the InvoiceNumber.
-- Combine a seed with a computed column.
CREATE TABLE #Example
(
Seed INT IDENTITY(1,1),
InvoiceNumber AS 'A' + CAST(Seed AS VARCHAR(5)),
Customer VARCHAR(25)
);
-- Add some sample records.
INSERT INTO #Example
(
Customer
)
VALUES
('A PLC'),
('B PLC'),
('C LTD')
;
-- Returns InvoiceNumbers A1, A2 & A3.
SELECT
*
FROM
#Example
;

Related

SQL Server : check not existing number into a table

I have a Clients table already populated by thousands of records and now I need to search for a non-existing number in the card number column starting from the number x.
Example: I would like to search for the first available card number starting from number 2000.
Unfortunately I cannot select MAX() as there are records with 9999999 (which is the limit).
Is it possible to do this search through a single SELECT?
It's possible with a few nested SELECTs:
SELECT MIN(`card_number`) + 1 as next_available_number
FROM( SELECT (2000-1) as `card_number`
UNION
SELECT `card_number`
FROM clients
WHERE `card_number` >= 2000
) tmp
WHERE NOT EXISTS ( SELECT NULL
FROM clients
WHERE `card_number` = tmp.`card_number` + 1 )
It can be done with a self-join on your clients table, where you search for the lowest cardnumber for which the cardnumber + 1 does not exist.
In case x is 12, the query would be:
SELECT MIN(cardnumber) + 1
FROM clients
WHERE cardnumber + 1 NOT IN (SELECT cardnumber FROM clients)
AND cardnumber + 1 > 12
Eg. with a dataset of
INSERT INTO clients (cardnumber) VALUES
(1),(2),(3),(4),(5),(6),(7),(8),(9),(11),(12),(13),(14),(15),(17),(18)
this returns 16, but not 10.
Example on SQL Fiddle.
I think this is very similar to this question, but the minimum criteria is new.
If the credit card is represented as integer in your table and your starting number is 2000 you could do something like:
SELECT top 1 (card_id + 1)
FROM CreditCards t
WHERE card_id IN (
SELECT card_id
FROM CreditCards
WHERE card_id LIKE '%[2][0][0][0]%'
)
AND NOT EXISTS (SELECT 1 FROM CreditCards t2 WHERE t2.card_id = t.card_id + 1)
ORDER BY card_id
Example data (Table: CreditCards):
card_id
2000002
2000103
2000000
2000108
2000106
3000201
1000101
Result is: 2000001
Note that %[2][0][0][0]% is fixed here. You could also introduce a parameter.
It is not an optimal solution, but it does the trick.

How to add alphabet increment?

i have this table
series
id
1975
1
1985
1
1995
2
2000
2
what we trying to achieve is we add alphabet increment where id is same, example series will be 1975A, 1985B, and then 1995A 2000B when id is same, it is possible to do that? in query or in c# mvc code?
You can use below query.
At first,
I have added row number par group/ partition
Then as we know CHR(65)='A', Thus I have added 64 + auto row_rumber
And Convert to CHAR.
Add result with series field.
SELECT
CONCAT
(
series ,
CHR(64 + CAST ( row_number() OVER(PARTITION BY id order by id) AS integer ))
)
,id from table1

TSQL Transpose a column of a table into a row

I have a temporary table with one column containing 3 pieces of data: Code, Date, and Quantity.
Example:
-------
FR123456
24/02/1988
500
I need to extract the data in this column into separate columns.
Example:
Code | Date | Quantity
--------- ----------- ----
FR123456 | 24/02/1988 | 500
I used this code:
SELECT [1], [2], [3]
FROM
(
SELECT row_number() OVER (ORDER BY splitdata DESC) AS Id, splitdata
FROM splitdata
) AS SourceTable
PIVOT
(
MIN (splitdata)
FOR id IN ([1], [2], [3])
) AS PivotTable;
The problem with it is that once the content of data changes, I may get the quantity content into the date column due to the aggregate function (MIN).
I assume this is SQL-Server related...
Your problem is: A SQL-Server table does not have any kind of implicit sort order. A simple SELECT * FROM SomeWhere can return in the sort order you've inserted your data, but can return completely different as well. The only chance to ensure a sort order is an ORDER BY at the outer-most query against a (set of) unique column(s).
You can create a sort order by kind of analysing your data:
This is a mockup-table with your test data:
DECLARE #mockup TABLE(YourColumn VARCHAR(100));
INSERT INTO #mockup VALUES
('FR123456')
,('24/02/1988')
,('500');
--The query will check the values if they can be casted to a number, to a date or not.
--This will be used to place a sort order to the values.
--I use 105 in CONVERT to enforce the dateformat dd-MM-yyyy
SELECT CASE WHEN TRY_CONVERT(DATE,YourColumn,105) IS NOT NULL THEN 2
ELSE CASE WHEN TRY_CAST(YourColumn AS INT) IS NOT NULL THEN 3 ELSE 1
END
END AS SortOrder
,YourColumn
FROM #mockup
ORDER BY SortOrder;
But if there are several triplets in your table, not just one as in your sample, I'm afraid you're lost...
Btw: Your own approach tries to do exactly the same:
SELECT row_number() OVER (order by splitdata desc)as Id
This will create kind of a sort order number, but it will be random (a quantity will appeare before or after the date depending on alphanumerical rules).
Hint
Add an IDENTITY column to your table. This will use an increasing number for any row the moment it is created. These values can be used to enforce the order as inserted (by using ORDER BY with this column).
UPDATE: Your query
SELECT [1], [2] , [3]
FROM
(SELECT CASE WHEN TRY_CONVERT(DATE,splitdata,105) IS NOT NULL THEN 2
ELSE CASE WHEN TRY_CAST(splitdata AS INT) IS NOT NULL THEN 3 ELSE 1
END
END AS Id , splitdata
from #mockup ) AS SourceTable
PIVOT
(
MIN (splitdata)
FOR id IN ([1], [2], [3])
) AS PivotTable;

How to grab last row in database table with specific requirements?

Okay so I am accepting payments on my site (via Authorize.Net). The payment form redirects to a receipt page.
I will have a column in the database for an invoice code (column InvoiceCode), which is RRC0A in this instance. Then I will have another column for an 8 digit number (column InvoiceNumber). Then I will have InvoiceCode + InvoiceNumber = InvoiceId. For example, the InvoiceId will be RRC0A + 8 numbers. It will increment as such: 00000000, 00000001, 00000002, etc. Therefore the InvoiceId will be RRC0A00000001. I cannot simply increment the column in my database because there will be other InvoiceCodes that also start at 00000000.
I need to increment the InvoiceNumber by one when I add a new row. How can I grab the last InvoiceNumber that was entered into the database? It must be associated with the InvoiceCode RRC0A. This could occur when more than 1 person is making a payment, so I am not sure of the best way.
How can I pad the incrementing InvoiceNumber with 0's in front so that it is always 8 digits?
Using an identity and a computed column you can created you invoice numbers with the correct formatting at the time of insert.
CREATE TABLE [dbo].[Invoices](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Code] [nchar](5) NOT NULL,
[InvoiceNumber] AS ([Code]+right('00000000'+CONVERT([nvarchar](10),[ID]),(8))) PERSISTED,
[Cost] [decimal](18, 2) NOT NULL,
CONSTRAINT [PK_Invoices] PRIMARY KEY CLUSTERED
(
[ID] ASC
)
)
sample bulk insert
INSERT INTO [dbo].[Invoices] ([Code], [Cost])
OUTPUT INSERTED.*
SELECT 'ABC01', 500 UNION ALL
SELECT 'ABC01', 501 UNION ALL
SELECT 'EFG23', 502 UNION ALL
SELECT 'RRAc1', 503 UNION ALL
SELECT 'ABC01', 504
output
ID Code InvoiceNumber Cost
1 ABC01 ABC0100000001 500.00
2 ABC01 ABC0100000002 501.00
3 EFG23 EFG2300000003 502.00
4 RRAc1 RRAc100000004 503.00
5 ABC01 ABC0100000005 504.00
When you insert your records you can get the ID and InvoiceNumber back at the same time.
The values are also persisted so they may be indexed as you would other columns.
SELECT InvoiceCode, MAX(InvoiceID)
FROM yourTable t
GROUP BY InvoiceCode
This should return the latest InvoiceID for each InvoiceCode, but you can add your own WHERE clause to filter it down
As for how to pad-left in sql, check out this answer.
A as in one column is just a bad design
Have composite PK
InvCode (varchar), InvInt (int)
declare #InvCode varchar(20) = 'RRC0A'
insert into invoice (InvCode, InvInt)
OUTPUT INSERTED.InvInt, INSERTED.InvCode
select #InvCode, isnull(max(InvInt),-1) + 1
from invoice
where InvCode = #InvCode;
The isnull will deal with the first one
A single statement is a transaction so I don't think two simultaneous could clobber
Even if they did the PK would be violated so the insert would fail
use a view or a computed column for the formatted invoice number
CREATE TABLE [dbo].[Invoice](
[InvCode] [varchar](10) NOT NULL,
[InvInt] [int] NOT NULL,
[Formatted] AS ([InvCode]+right('00000000'+CONVERT([nvarchar](10),[InvInt]),(8))),
CONSTRAINT [PK_Invoice] PRIMARY KEY CLUSTERED
(
[InvCode] ASC,
[InvInt] ASC
)
You can grab the last InvoiceNumber with a SELECT query.
You can pad the invoice number with the + sign to concatenate two strings, and then use RIGHT() to get the right-most 8 characters.

How to sort varchar type column that contain both string and numeric values

I have a table that has column name "BatchNo" and it contain both string and numeric values together. when i typed a select query i got following results.
i want to sort "BatchNo" column in following format
In my problem future batches may be have a,b,c .... letters with numeric values or only numeric values. how can i sort this column ? Hope you guys can help me to get some solution.
Why don't you alter the schema of your table into?
CREATE TABLE tableName
(
ShipmentNo INT,
ProjectCode VARCHAR(50),
BatchNo INT,
SubBatch INT,
.....
)
in this way, it is to sort the valkues the way you want.
follow-up question, is BatchNo has only single character value from A-Z, eg
11a
11b
and not
11aa
UPDATE 1
SELECT *
FROM tableName
ORDER BY CASE ISNUMERIC(batchNo)
WHEN 1 THEN batchNo
ELSE CAST(LEFT(batchNo, LEN(batchNo) - 1) AS INT)
END
SQLFiddle Demo
try this:
SELECT *
FROM tableName
ORDER BY
CAST(LEFT(BatchNo, PATINDEX('%[^0-9]%', BatchNo + 'Z')-1) AS INT),
BatchNo
SQL fiddle demo
How about this:
SELECT *
FROM TABLE_NAME
ORDER BY CAST(LEFT(BatchNo, PATINDEX('%[^0-9]%', BatchNo + 'A')-1) AS INT)
Query works for a string which starts with numeric values only.

Categories