Auto increment primary key and reseed every month - sql

What is the best solution to create SQL table which has a composite primary key.
First column of the primary key is ID {int}.
Second column of the primary key is YearMonth {string like yyyyMM ex. 201409 } which is current month.
that can reseed an ID to 1 every month
And I actually need the running ID like
"201409-00001"
"201409-00002"
"201409-00003"
.
.
"201410-00001"
"201410-00002"
.
.
"201411-00001"

Based on the question and your comments, it seems that you need to display the a row identifier in the format 201411-00001. This does not need to be your actual primary key. What I would recommend is that you do something like this.
create your table with ID which is Identity. Add another column YearMonth CHAR(6) column which stores YYYYMM or if you already have a column which stores the date as date/datetime, use that. In your SELECTs you would do something like this
LEFT(CONVERT(VARCHAR(10),YearMonth,112),6) + '-' + RIGHT(REPLICATE('0',5) + CONVERT(VARCHAR(5),ROW_NUMBER() OVER(PARTITION BY DateCol, ORDER BY ID),5)
You would alternately have a trigger which updates a new INT column monthlyID based on the MAX(monthlyID) + 1 for the month.

Create sequence start at 1 and concat it to your 'year,month'
Create job at every 1st of month and restart the sequence

Did you try concatenating them and creating a new column to make it the primary key?
Don't know if there is a simpler method,but this should work:
SELECT CONCAT(YEAR(CURRENT_TIMESTAMP), MONTH(CURRENT_TIMESTAMP),'-',ID)
FROM <TABLE NAME>;

Finally, I try using the concept of Mr. #ughai
and I using the query like below to keep the values on another column for represent the ID with month relatively.
select LEFT(CONVERT(VARCHAR(10),YearMonth,112),6) + '-' + RIGHT(REPLICATE('0',4) + CONVERT(VARCHAR(5),ROW_NUMBER() OVER(PARTITION BY LEFT(CONVERT(VARCHAR(10),YearMonth,112),6) ORDER BY ID)),5) from TestTable

Try something like this:
ALTER TABLE table_name AUTO_INCREMENT = 1
and this:
ALTER TABLE foobar_data MODIFY COLUMN col VARCHAR(255) NOT NULL DEFAULT '201409';
and run this query via some method every month ;)

Related

Assign a value if the field is not null

I'm working on a SQL project on MS Access.
I would like to know if there is a way to assign a same value everytime a field is NOT NULL. I know that there is the Nz() function which does the opposite, but I don't know other functions.
Also, I would like to put a different value everytime the field is NULL
My table looks like that.
date
MARCH17
JUNE18
JULY19
and I would like to get something like that.
date
1
2
PRESENT
PRESENT
5
PRESENT
If I have to create another column, it's perfectly fine too.
Thanks in advance !
You will need to place your new information in a new column, otherwise, if you run the query more than once, you will get PRESENT for everything since the first query replaces the NULL date with a sequence number.
If you have an id column you can use:
UPDATE table SET new_column = (SELECT IIF(date IS NULL, id,'PRESENT'))
If you don't have an id column (which is strongly recommended) then you'll need to generate a sequence number.
Does your table have a Primary Key? Then you want to count all nulls where primary key is less than this one to give you your number, and put present where it isn't null. So (assuming your field is F1 and Primary Key is called PK) the following calculated field
=IIf(ISNULL([F1]),DCOUNT("[PK]","MYTABLE","[PK]<" & [PK]) &""","PRESENT")
You can use:
UPDATE
YourTable
SET
[date] = IIf([date] Is Null,
(Select Count(*) + 1 From YourTable As T Where T.[date] <> 'PRESENT'),
'PRESENT'))
WHERE
[date] <> 'PRESENT'

Need to assign an auto increment value to the varchar column of table and table without using in I'd column as auto increment

I had a table of Transaction, in that table I don't have any ID column. I have to generate a unique value in the form of "0901201900001".
Above format is the combination of today's date and the value 00001.
00001 - it's autoincremented value for the same day only. Next day it should start with 00001 again.
Output should be like this
0901201900001
0901201900002
0901201900003
.
.
.
09012019000050
1001201900001
.
.
.
10012019000050
I agree with what #Sean Lange says, this is gross. Combining a date and a generated number is taking two pieces of data (date and a surrogate key) and making them one column. You are always going to be parsing out what the data is and trying to figure out what the date is. Instead you want to make your key a date and the sequence id.
That being said, here is something that you can do to address your original problem.
CREATE SEQUENCE dbo.SQ_RestartableSequence AS INT INCREMENT BY 1 START WITH 1 CYCLE
-- Run this every day right before midnight. Gross, but it's the only way to get what you want
ALTER SEQUENCE dbo.SQ_RestartableSequence RESTART WITH 1
CREATE TABLE SequenceTest
( ID VARCHAR(30) DEFAULT REPLACE(CONVERT(VARCHAR(30), CAST(SYSDATETIME() AS DATE), 1), '/', '') + RIGHT( '0000' + CAST(NEXT VALUE FOR SQ_RestartableSequence AS VARCHAR(30)), 4)
, ValueField Varchar(30)
)
INSERT INTO dbo.SequenceTest
(ValueField)
VALUES
( 'Test Value')
INSERT INTO dbo.SequenceTest
(ValueField)
VALUES
( 'Test Value2')
SELECT *
FROM dbo.SequenceTest AS st

Generate sequence number in SQL on every insert

I need to enter primary key in table as in below format
YYYY/MMM/NNNNNN
Where, YYYY is the current year, MMM is Month , and NNNNNN is a sequence no from 000001, 000002, 000003, .... 999999.
So my primary key will look like 2012/Oct/000001 or 2012/Oct/000010 ....
How can I generate this type of code..
I can get Year and Month from Getdate() function. But how can I manage sequence number on every insert. can you please give me logic for that?
By far the easiest way would be to let SQL Server handle the dishing out of consecutive numbers using an INT IDENTITY column - and then use a trigger to create that specific format that you need, in a separate column.
So given this table:
CREATE TABLE SampleTable
(ID INT IDENTITY, SaleDate DATE, ComputedPK VARCHAR(25) )
you could use a trigger like this to compute the ComputedPK from the ID (autonumber, handled by SQL Server) and the SaleDate as the date column:
CREATE TRIGGER trgSampleTableInsert
ON dbo.SampleTable FOR INSERT
AS
UPDATE dbo.SampleTable
SET ComputedPK = CAST(YEAR(i.SaleDate) AS CHAR(4)) + '/' + DATENAME(MONTH, i.SaleDate) + '/' + RIGHT('000000' + CAST(i.ID AS VARCHAR(6)), 6)
FROM dbo.SampleTable s
INNER JOIN INSERTED i ON s.ID = i.ID
This approach will not start at 1 for each month, however - but do you really need that? Isn't a sequential number (even across months) good enough?
Update: of course, if you're using SQL Server 2012 (you didn't specify which version of SQL Server you're using...) - you could use a SEQUENCE object to handle the consecutive numbering - and you could even reset that sequence to 1 again every start of a month ....
SELECT
CONCAT(
DATEPART(YEAR, GETDATE()),
'/',
DATENAME(MONTH,GETDATE()),
'/',
REPLACE(STR(((SELECT COUNT(*) FROM yourtable WHERE monthname = DATENAME(MONTH,GETDATE()) GROUP BY monthname) + 1),6,0),' ','0')
)
)
This is untested now tested. You would have to add a monthname column (there is a way of doing this without adding a column, but this is the most convenient)
You can also cast and use addition if you don't want to rely on concat. http://sqlfiddle.com/#!6/3e43d/6
Why don't you just consider a compound key with an identity/numeric column and a date column (or if the day is not needed, the year/month)?
This would give you the same behaviour and would probably be a bit simpler to implement/maintain
I still would like to know the reasoning behind this - just so we can make a better educated guess
Set your Primary Key on two columns. One of them will represent the Daten and the other one the Serial number. Set a Sequence on the Serial column which increases automatically. This will make it easier for you filter the Date part of the Key.

Concatenate value to generated unique ID

I have an existing table named Employee and have to add a new column Employee_Id.
EmployeeId should be 10 digit unique number and always have to start with 10.
For example
1000000000
1000000001
1023456789
So I need to add bunch of unique 10 digit Id's to an existing table which already has data.
Can anyone help me sort this out.
SELECT 1000000000 + ROW_NUMBER() OVER( ORDER BY YourColumn ) AS 'rownumber',*
FROM Employee
This will get the data from the existing table, with an extra column for the new id.
If you are using SQL Server, IDENTITY would help you.
http://msdn.microsoft.com/en-us/library/ms186775.aspx
Update: You should see the discussion here in order to alter table.
Adding an identity to an existing column
If you already have and integer PK, you may add a calculated column (persisted or not). It value will be PK + 1000000000, provided no pk is bigger than 1000000000.
ALTER TABLE YOURTABLE
ADD COLUMNNAME INTEGER IDENTITY(1000000000, 1)
It will not generate all with 10.. but it will generate al the possibilities, if it get passed you will get 11.. but that would be a lot of numbers to reach that.
Hope it helps

Generating Random ID's in Microsoft SQL Server

I want to create a table in sql server and fill it up with data (people's info) every person should have a unique ID different than the auto incremented ID's by sql server
For example i need the ID for the first person inserted like this: 2016xxxx
how to fix the 2016 and randomly generate the numbers after that to be filled instead of xxxx
should i use a regular expression ?
You can also create a computed column like below
CREATE TABLE tableName
(
PkAutoId INT PRIMARY KEY IDENTITY(1,1),
PersonUniqueNo AS (CAST(DATEPART(YEAR,GETDATE()) AS VARCHAR) + RIGHT(RIGHT(CAST(RAND() AS VARCHAR),4) + CAST(PkAutoId AS VARCHAR),4))
)
Computed Column "PersonUniqueNo" is 8 Digit Unique Number comprising of Current Year And Conceited value of Random number and Primary Key Id for 4 Length, Total length will be 8 as asked.
You could create a function that would get the next value for you and use that instead of an AUTO_INCREMENT field.
I wouldn't recommend it tho. You shouldn't format the data like that before inserting it. That sort of thing should be done on the way out, preferably by the front-end code. Or you can just write a query and create a view ...
However if you must do that here is the complete answer with the code:
Is there a way to insert an auto-incremental primary id with a prefix in mysql database?