how to generate a number following a pattern using sql? - sql

I want to generate a pattern in SQL Server.
e.g. PA0001
and increment it every time (meaning if PA0001 has already been generated the next should be PA0002 and so on).
I have no idea how to go about this!
Can anyone help?

The canonical way is to have an indentity column and then create this code as a computed column:
create table . . . (
inc int not null identity(1, 1),
. . .
code as ('PA' + right('0000' + cast(inc as varchar(255)), 4)
This only works with one prefix -- if you want all values to start with 0001. If you have multiple prefixes, you can:
Use a trigger.
Calculate the code in queries.
Change your requirements so you can use codes that do not have other meanings.

You can write as:
create table Test
(
ID int identity not null primary key,
pattern varchar(100)
)
Go
create function Nextpattern (#id int)
returns varchar(20)
as
begin
return 'PA' +
CONVERT(VARCHAR(10), GETDATE(), 110) + right('00' + convert(varchar(10), #id), 2)
end
--Solution 1:
Go
alter table Test add Newpattern as dbo.Nextpattern(ID)
Go
insert into Test values (1)
Go
--solution2:
-- not good as what if two processes attempt to
-- add a row to the table at the exact same time?
create function dbo.fnNextpattern()
returns varchar(20)
as
begin
declare #lastval varchar(20)
set #lastval = (select max(pattern) from Test)
if #lastval is null set #lastval = 'PA' +
CONVERT(VARCHAR(10), GETDATE(), 110) + '01'
declare #i int
set #i = right(#lastval,2) + 1
return 'PA' +
CONVERT(VARCHAR(10), GETDATE(), 110)+ right('00' + convert(varchar(10),#i),2)
end
go
DEMO

Related

Generating a Primary Key Column by using the specific number

I need to insert the numbers that fall between the Start and End column in the column "NumberList" (This should include both the Start and End numbers).
The query that I am using to get the above result is as follows
SELECT DISTINCT Number
, CONVERT(VARCHAR,Number) + REPLICATE('0',16-LEN(Number)) AS 'Start'
, CONVERT(VARCHAR,Number) + REPLICATE('9',16-LEN(Number)) AS 'End'
,NULL 'NumberList'
FROM Table
Could you please help me with the following as I would like the NumberList column to be a Primary Key too
Create function GetNumbersList (#intStart as bigint, #intEnd as bigint)
returns varchar(max)
as
begin
DECLARE #num INT = #intStart
DECLARE #numberlist as varchar(max)=''
WHILE(#num<=#intEnd)
begin
set #numberlist=#numberlist + cast(#num as varchar(20)) + N' '
SET #num = #num + 1
end
return(rtrim(#numberlist))
End
GO
select Number
, CONVERT(VARCHAR,Number) + REPLICATE('0',16-LEN(Number)) AS 'Start'
, CONVERT(VARCHAR,Number) + REPLICATE('9',16-LEN(Number)) AS 'End'
, dbo.GetNumbersList (CONVERT(VARCHAR,Number) + REPLICATE('0',16-LEN(Number)), CONVERT(VARCHAR,Number) + REPLICATE('9',16-LEN(Number))) as [NumbersList]
from Table

SQL Server: auto-generated custom format sequence number

I am working with Microsoft SQL Server 2014. In our requirement, custom formatted sequence number is include.
The sequence number format is CAT-YYYY-MM-NNNNNN. Sample data:
CAT-2016-10-000001
CAT-2016-10-000002
.
.
.
CAT-2016-10-999999
I don't want to use GUID or any other and I want to work with a procedure or function.
So, I am trying with this:
CREATE TABLE [category]
(
[id] int NOT NULL UNIQUE IDENTITY,
[category_no] nvarchar(20) NOT NULL,
[category_name] nvarchar(50) NOT NULL,
PRIMARY KEY ([id])
);
CREATE FUNCTION generate_category_no()
RETURNS CHAR(20)
AS
BEGIN
DECLARE #category_no CHAR(20)
SET #category_no = (SELECT MAX(category_no) FROM category)
IF #category_no IS NULL
SET #category_no = 'CAT-' + YEAR(getDate()) + '-' + MONTH(getDate()) + '-000001'
DECLARE #no int
SET #no = RIGHT(#category_no,6) + 1
RETURN 'CAT-' + YEAR(getDate()) + '-' + MONTH(getDate()) + '-' + right('00000' + CONVERT(VARCHAR(10),#no),6)
END
GO
ALTER TABLE category DROP COLUMN category_no;
ALTER TABLE category ADD category_no AS dbo.generate_category_no();
INSERT INTO category (category_name)
VALUES ('BMW'), ('JAGUAR');
When I run the above SQL in step-by-step, it is OK. It shown no error. But when I run the following command:
SELECT * FROM category;
it shows the following error:
Msg 217, Level 16, State 1, Line 1
Maximum stored procedure, function, trigger, or view nesting level exceeded (limit 32).
I don't know how to solve this one. And even I don't know my function has worked or not. I referenced from internet for this function.
ADDED
I need to reset sequence no for every month. Eg. for next month, no should be as follow:
CAT-2016-11-000001
Please, enlighten me. Thanks in advance!
Modify your function as below
ALTER TABLE category DROP COLUMN category_no;
alter FUNCTION dbo.generate_category_no( #id int)
RETURNS CHAR(20)
AS
BEGIN
RETURN 'CAT-' + cast(YEAR(getDate()) as varchar(10)) + '-' + cast(MONTH(getDate()) as varchar(10))+ '-' + right('00000' + CONVERT(VARCHAR(10),#id),6)
END
ALTER TABLE category ADD category_no AS dbo.generate_category_no(id);
INSERT INTO category
(category_name)
VALUES
('BMW13'),
('JAGUAR');
SELECT * FROM category will give the below result.
1 BMW CAT-2016-10-000001
2 JAGUAR CAT-2016-10-000002
3 BMW1 CAT-2016-10-000003
4 BMW13 CAT-2016-10-000004
Try this:
To initialize your new field:
ALTER TABLE category DROP COLUMN category_no;
ALTER TABLE category ADD category_no CHAR(20)
UPDATE category set category_no = dbo.generate_category_no()
For other insert:
CREATE TRIGGER [dbo].[category_i]
ON [dbo].[category]
AFTER INSERT
AS BEGIN
UPDATE category
SET category_no = dbo.generate_category_no()
FROM inserted
WHERE category.pk = inserted.pk
END
But you can try to use SEQUENCE feature, available on Sql Server by 2012 version
About SEQUENCE you can see here
Biggest flaw in your function is it will not work for Batch Insert's
Since you have ID auto generated, here is a easier way to do this
category_no AS Concat('CAT-', Year(Getdate()), '-', Month(Getdate()), '-', RIGHT(Concat('00000', id), 6))
Demo
CREATE TABLE #seq
(
id INT IDENTITY(1, 1),
name VARCHAR(10),
category_no AS Concat('CAT-', Year(Getdate()), '-', Month(Getdate()), '-', RIGHT(Concat('00000', id), 6))
)
INSERT INTO #seq
(name)
VALUES ('val')
Result :
id name category_no
-- ---- -----------
1 val CAT-2016-10-000001
Finally, I solved the problem. My Function look like as follow:
CREATE FUNCTION generate_category_no()
RETURNS CHAR(20)
AS
BEGIN
DECLARE #category_no CHAR(20)
SET #category_no = (SELECT MAX(category_no) FROM category WHERE category_no LIKE CONCAT('CAT-', YEAR(getDate()), '-', MONTH(getDate()), '-%'))
IF #category_no is null SET #category_no = CONCAT('CAT-', YEAR(getDate()), '-', MONTH(getDate()), '-000000')
DECLARE #no INT
SET #no = RIGHT(#category_no,6) + 1
RETURN CONCAT('CAT-', YEAR(getDate()), '-', MONTH(getDate()), '-', RIGHT('00000' + CONVERT(VARCHAR(10),#no),6))
END
GO
And I insert data as follow:
INSERT INTO category (category_no, category_name) VALUES (dbo.generate_category_no(),'BMW');
INSERT INTO category (category_no, category_name) VALUES (dbo.generate_category_no(),'JAGUAR');
One things is that We can call function from INSERT query.
So, when I run the following sql:
SELECT * FROM category;
It give the result as shown in below.
+---+--------------------+--------------+
|id |category_no |category_name |
+---+--------------------+--------------+
| 1 |CAT-2016-10-000001 | BMW |
| 2 |CAT-2016-10-000002 | JAGUAR |
+---+--------------------+--------------+
Thanks everybody for helping me. Thanks!!!

Need to auto increment string in SQL Server 2012

Consider the table in SQL Server 2012
789-0000000
The above number will be consider as a string in SQL Server 2012, but whenever I update the record I need increment to 1.
For example:
When I update the record 1 it should increment to 789-0000001
When I update the record 2 it should increment to 789-0000002
Finally increment should done only 789-0000000
The best solution is to use
an ID INT IDENTITY(1,1) column to get SQL Server to handle the automatic increment of your numeric value
a computed, persisted column to convert that numeric value to the value you need
So try this:
CREATE TABLE dbo.YourTable
(ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
CompanyID AS '789-' + RIGHT('000000' + CAST(ID AS VARCHAR(7)), 7) PERSISTED,
.... your other columns here....
)
Now, every time you insert a row into dbo.YourTable without specifying values for ID or CompanyID:
INSERT INTO dbo.YourTable(Col1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)
then SQL Server will automatically and safely increase your ID value, and CompanyID will contain values like 789-0000001, 789-0000002,...... and so on - automatically, safely, reliably, no duplicates.
DECLARE #base int = 0
UPDATE TableX
SET
TableX.Value = 'Prefix' + RIGHT('0000000' + CAST(#base AS nvarchar),7),
#base = #base + 1
FROM
TableX
you can split the string
e.g.:
SELECT Item
FROM dbo.SplitString('Apple,Mango,Banana,Guava', ',')
then cast it
e.g.:
SELECT CAST(YourVarcharCol AS INT) FROM Table
then manually increment it
e.g.:
DECLARE max_id INT
SET #max_id = (SELECT MAX(id) FROM source_table)
DECLARE cursor_name CURSOR FOR
SELECT columns, to, copy
FROM source_table
OPEN cursor_name
FETCH NEXT FROM cursor_name
INTO #columns, #to, #cop
at update
e.g.:
declare #i int = SELECT ISNULL(MAX(interfaceID),0) + 1 FROM prices
update prices
set interfaceID = #i , #i = #i + 1
where interfaceID is null
you can understand how complicate this is and why
the solution using a constant to store that prefix is right one.
Declare #str varchar(max) = '789-0000000'
Select
SUBSTRING ( #str ,0 ,CHARINDEX ( '-' ,#str ))
+'-'
+
(SUBSTRING ( #str ,(CHARINDEX ( '-' ,#str)+1) ,(7-LEN(CAST(SUBSTRING ( #str ,CHARINDEX ( '-' ,#str)+1,LEN(#str)) as int))
)
)+
CAST(CAST(SUBSTRING ( #str ,CHARINDEX ( '-' ,#str)+1,LEN(#str)) as int)+1 as varchar))
When #str='789-0001947'
Output #str= 789-0001948
You can write a update trigger on the table with above logic.

Auto increment Alphanumeric ID in MSSQL

I have an existing Stored procedure that generate employee ID. The employee ID have a format of EPXXXX, EP then 4 numeric values. I want my stored procedure to be shorten.
given the table (tblEmployee) above. Below is the stored procedure for inserting the new employee with the new employee number. The process is I have to get the last employee id, get the last 4 digits (which is the number), convert it to integer, add 1 to increment, check if the number is less than 10, 100 or 1000 or equal/greater than 1000, add the prefix before inserting the new records to the table.
create procedure NewEmployee
#EmployeeName VARCHAR(50)
AS
BEGIN
SET NOCOUNT ON
DECLARE #lastEmpID as VARCHAR(6)
SET #lastEmpID =
(
SELECT TOP 1 Employee_ID
FROM tblEmployee
ORDER BY Employee_ID DESC
)
DECLARE #empID as VARCHAR(4)
SET #empID =
(
SELECT RIGHT(#lastEmpID, 4)
)
DECLARE #numEmpID as INT
#numEmpID =
(
SELECT CONVERT(INT, #empID) + 1
)
DECLARE #NewEmployeeID as VARCHAR(6)
IF #numEmp < 10
SET #NewEmployee = SELECT 'EP000' + CONVERT(#EmpID)
IF #numEmp < 100
SET #NewEmployee = SELECT 'EP00' + CONVERT(#EmpID)
IF #numEmp < 1000
SET #NewEmployee = SELECT 'EP0' + CONVERT(#EmpID)
IF #numEmp >= 1000
SET #NewEmployee = SELECT 'EP' + CONVERT(#EmpID)
INSERT INTO tblEmployee(Employee_ID, Name)
VALUES (#NewEmployeeID, #EmployeeName)
END
Try this one -
CREATE PROCEDURE dbo.NewEmployee
#EmployeeName VARCHAR(50)
AS BEGIN
SET NOCOUNT ON;
INSERT INTO dbo.tblEmployee(Employee_ID, Name)
SELECT
'EP' + RIGHT('0000' + CAST(Employee_ID + 1 AS VARCHAR(4)), 4)
, #EmployeeName
FROM (
SELECT TOP 1 Employee_ID = CAST(RIGHT(Employee_ID, 4) AS INT)
FROM dbo.tblEmployee
ORDER BY Employee_ID DESC
) t
END
I'm not suggesting over what you have currently but, i'd do this way. This is the way I've implemented in my application. Which im gonna give you. Hope you Like this. This is fully Dynamic and Works for all the Transaction you could have.
I've a table Which hold the Document Number as :
CREATE TABLE INV_DOC_FORMAT(
DOC_CODE VARCHAR(10),
DOC_NAME VARCHAR(100),
PREFIX VARCHAR(10),
SUFFIX VARCHAR(10),
[LENGTH] INT,
[CURRENT] INT
)
Which would hold the Data Like :
INSERT INTO INV_DOC_FORMAT(DOC_CODE,DOC_NAME,PREFIX,SUFFIX,[LENGTH],[CURRENT])
VALUES('01','INV_UNIT','U','',5,0)
INSERT INTO INV_DOC_FORMAT(DOC_CODE,DOC_NAME,PREFIX,SUFFIX,[LENGTH],[CURRENT])
VALUES('02','INV_UNIT_GROUP','UG','',5,0)
And, i'd have a fUNCTION OR Procedure but, i've an function here Which would generate the Document Number.
CREATE FUNCTION GET_DOC_FORMAT(#DOC_CODE VARCHAR(100))RETURNS VARCHAR(100)
AS
BEGIN
DECLARE #PRE VARCHAR(10)
DECLARE #SUF VARCHAR(10)
DECLARE #LENTH INT
DECLARE #CURRENT INT
DECLARE #FORMAT VARCHAR(100)
DECLARE #REPEAT VARCHAR(10)
IF NOT EXISTS(SELECT DOC_CODE FROM INV_DOC_FORMAT WHERE DOC_CODE=#DOC_CODE)
RETURN ''
SELECT #PRE= PREFIX FROM INV_DOC_FORMAT WHERE DOC_CODE=#DOC_CODE
SELECT #SUF= SUFFIX FROM INV_DOC_FORMAT WHERE DOC_CODE=#DOC_CODE
SELECT #LENTH= [LENGTH] FROM INV_DOC_FORMAT WHERE DOC_CODE=#DOC_CODE
SELECT #CURRENT= [CURRENT] FROM INV_DOC_FORMAT WHERE DOC_CODE=#DOC_CODE
SET #REPEAT=REPLICATE('0',(#LENTH-LEN(CONVERT(VARCHAR, #CURRENT))))
SET #FORMAT=#PRE + #REPEAT +CONVERT(VARCHAR, #CURRENT+1) + #SUF
RETURN #FORMAT
END
You can use the Function like :
INSERT INTO INV_UNIT(UNIT_CODE,UNIT_NAME,UNIT_ALIAS,APPROVED,APPROVED_USER_ID,APPROVED_DATE)
VALUES(DBO.GET_DOC_FORMAT('01'),#Unit_Name,#Unit_Alias,#APPROVED,#APPROVED_USER_ID,#APPROVED_DATE)
--After Transaction Successfully complete, You can
UPDATE INV_DOC_FORMAT SET [CURRENT]=[CURRENT]+1 WHERE DOC_CODE='01'
Or, you can create an Single Procedure which would handle all the things alone too.
Hope you got the way...
Hence,
Looking at your Way, you are making an Mistake.
You are getting
SET #lastEmpID =
(
SELECT TOP 1 Employee_ID
FROM tblEmployee
ORDER BY Employee_ID DESC
)
Last employee id, and then you are manipulating the rest of the ID. This would create or reuse the ID that was generated earlier however deleted now.
Suppose EMP0010 was there. After some day that EMP has been Deleted. So, When you again create an Employeee next time, You gonna have Same Emp ID you had before for anohter Employe but no more exits however. I dont think thats a good idea.
And, Instead of this :
DECLARE #NewEmployeeID as VARCHAR(6)
IF #numEmp < 10
SET #NewEmployee = SELECT 'EP000' + CONVERT(#EmpID)
IF #numEmp < 100
SET #NewEmployee = SELECT 'EP00' + CONVERT(#EmpID)
IF #numEmp < 1000
SET #NewEmployee = SELECT 'EP0' + CONVERT(#EmpID)
IF #numEmp >= 1000
SET #NewEmployee = SELECT 'EP' + CONVERT(#EmpID)
Which you used to repeat an Zero. You would use Replicate Function() of SQL. Like above on the Example of Mine.
SET #REPEAT=REPLICATE('0',(#LENTH-LEN(CONVERT(VARCHAR, #CURRENT))))
I don't think you need a Stored Procedure , Try using Ranking Functions
select
'EP'+RIGHT('000000'+ CAST(ROW_NUMBER() OVER (ORDER BY Name) AS VARCHAR(6)), 4)
AS [emp_code]
,
Name
FROM emp1 WITH(NOLOCK)
SQL Fiddle
EDIT
select
'EP'+RIGHT('000000'+ CAST((ROW_NUMBER() OVER (ORDER BY Name)+10) AS VARCHAR(6)), 4)
AS [emp_code] --^Add the last Emp no.
,
Name
FROM emp1 WITH(NOLOCK)
SQL Fiddle
of course the accepted answer is working fine, but it is not working if we have numm in previous values. so modified it as below, hope this will help others as well
CREATE PROCEDURE dbo.NewEmployee
#EmployeeName VARCHAR(50)
AS BEGIN
SET NOCOUNT ON;
INSERT INTO dbo.tblEmployee(Employee_ID, Name)
SELECT
'EP' + RIGHT('0000' + CAST(Employee_ID + 1 AS VARCHAR(4)), 4)
, #EmployeeName
FROM (
SELECT TOP 1 Employee_ID = CAST(RIGHT(Employee_ID, 4) AS INT)
FROM dbo.tblEmployee
ORDER BY Employee_ID DESC
) t
END

SQL server - Split and sum of a single cell

I have a table cell of type nvarchar(max) that typically looks like this:
A03 B32 Y660 P02
e.g. a letter followed by a number, separated by spaces. What I want to do is get a sum of all those numbers in a SQL procedure. Something rather simple in other languages, but I am fairly new to SQL and besides it seems to me like a rather clumsy language to play around with strings.
Aaanyway, I imagine it would go like this:
1) Create a temporary table and fill it using a split function
2) Strip the first character of every cell
3) Convert the data to int
4) Update target table.column set to sum of said temporary table.
So I got as far as this:
CREATE PROCEDURE [dbo].[SumCell] #delimited nvarchar(max), #row int
AS
BEGIN
declare #t table(data nvarchar(max))
declare #xml xml
set #xml = N'<root><r>' + replace(#delimited,' ','</r><r>') + '</r></root>'
insert into #t(data)
select
r.value('.','varchar(5)') as item
from #xml.nodes('//root/r') as records(r)
UPDATE TargetTable
SET TargetCell = SUM(#t.data) WHERE id = #row
END
Obviously, the first char stripping and conversion to int part is missing and on top of that, I get a "must declare the scalar variable #t" error...
Question is not very clear so assuming your text is in a single cell like A3 B32 Y660 P20 following snippet can be used to get the sum.
DECLARE #Cell NVARCHAR(400), #Sum INT, #CharIndex INT
SELECT #Cell = 'A3 B32 Y660 P20',#Sum=0
WHILE (LEN(LTRIM(#Cell))>0)
BEGIN
SELECT #CharIndex = CHARINDEX(' ',#Cell,0)
SELECT #Sum = #Sum +
SUBSTRING(#Cell,2,CASE WHEN #CharIndex>2 THEN #CharIndex-2 ELSE LEN(#Cell)-1 END )
SELECT #Cell = SUBSTRING(#Cell,#CharIndex+1,LEN(#Cell))
IF NOT (#CharIndex >0) BREAK;
END
--#Sum has the total of cell numbers
SELECT #Sum
I'm making the assumption that you really want to be able to find the sum of values in your delimited list for a full selection of a table. Therefore, I believe the most complicated part of your question is to split the values. The method I tend to use requires a numbers table, So I'll start with that:
--If you really want to use a temporary numbers table don't use this method!
create table #numbers(
Number int identity(1,1) primary key
)
declare #counter int
set #counter = 1
while #counter<=10000
begin
insert into #numbers default values
set #counter = #counter + 1
end
I'll also create some test data
create table #data(
id int identity(1,1),
cell nvarchar(max)
)
insert into #data(cell) values('A03 B32 Y660 P02')
insert into #data(cell) values('Y72 A12 P220 B42')
Then, I'd put the split functionality into a CTE to keep things clean:
;with split as (
select d.id,
[valOrder] = row_number() over(partition by d.cell order by n.Number),
[fullVal] = substring(d.cell, n.Number, charindex(' ',d.cell+' ',n.Number) - n.Number),
[char] = substring(d.cell, n.Number, 1),
[numStr] = substring(d.cell, n.Number+1, charindex(' ',d.cell+' ',n.Number) - n.Number)
from #data d
join #numbers n on substring(' '+d.cell, n.Number, 1) = ' '
where n.Number <= len(d.cell)+1
)
select id, sum(cast(numStr as int))
from split
group by id