SQL Server - Create a custom auto-increment field - sql

I am trying to produce a custom auto-increment functionality in sql. my custom auto-incerement ID should be like below...
S1501.001
"S" is for Supplier's name first letter.
"15" is for this year's last 2 digits.
"01" is today's month
"." will always be there
"001" is my incrementer.
the counter will go on like below
S1501.001
S1501.002
S1501.003
S1501.004
Firstly, I have to find the "S1501." and find the ID with highest digits at the end. I can create a new "S1501.005". How can I do this?
I have done something but didnt work.
SELECT TOP 1 (SELECT SUBSTRING('S1501.001', 7,3)),*
FROM LG_001_01_SERILOTN
WHERE CODE LIKE SUBSTRING('S1501.001', 1,6)+'%'
ORDER BY (SELECT SUBSTRING('S1501.001', 7,3)) DESC

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.tblCompany
(ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
CompanyID AS 'S1501.' + RIGHT('000' + CAST(ID AS VARCHAR(3)), 3) PERSISTED,
.... your other columns here....
)
Now, every time you insert a row into tblCompany without specifying values for ID or CompanyID:
INSERT INTO dbo.tblCompany(Col1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)
then SQL Server will automatically and safely increase your ID value, and CompanyID will contain values like S1501.001, S1501.002,...... and so on - automatically, safely, reliably, no duplicates.

Related

How to create an insert trigger based on primary key?

I am stuck on a problem creating a trigger in SQL Server. I have MyTable with the following columns (simplified):
Sn - Identity, not nullable;
SomeId - int, not nullable;
miscellaneous other columns
The Sn column is nothing special, values 1,2...n.
SomeId needs to be 1000 + Sn, i.e. this is what I want the trigger to do on insert.
The problem I am having is a standard trigger fails if I don't include something for SomeId (error is that null is not allowed), if that trigger is using after insert. Maybe I am meant to use instead of insert, but I am having trouble getting that to work correct or find details about it.
The other factor here - I am not even sure if it is possible for what I am trying to do to work. I.e when a new row is being created and SQL Server generates an Sn (Identity column), can a trigger be part of that process and also compute the SomeId value (which needs the Sn value) before inserting?
If not, as a fallback I could either make the SomeId column nullable (not desirable), or always insert 0 into it (and let the trigger fire afterwards to update it), but that would be a bit grim also.
No need for a trigger. Just use a SEQUENCE to generate the ID values instead of an IDENTITY column, eg
create sequence seq_MyTable
start with 1
increment by 1
go
CREATE TABLE MyTable
(
Sn int not null primary key default (next value for seq_MyTable),
SomeID int not null unique default (next value for seq_MyTable) + 1000,
Name VARCHAR(50) NOT NULL
)
insert into MyTable(Name)
values ('A'),('B'),('C')
select * from Mytable

Auto Increment in String Value

I need query for auto increment in string value-
I need XS000001,XS000009....XS000099...XS000999,XS009999,XS099999,XS999999
Please help me...
If this is for SQL Server (you're not clear on which actual database you're using), 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,
AutoIncID AS 'XS' + RIGHT('000000' + CAST(ID AS VARCHAR(6)), 6) PERSISTED,
.... your other columns here....
)
Now, every time you insert a row into YourTable without specifying values for ID or AutoIncID:
INSERT INTO dbo.YourTable(Col1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)
then SQL Server will automatically and safely increase your ID value, and AutoIncID will contain values like XS000001, XS000002,...... and so on - automatically, safely, reliably, no duplicates.
But the question really is: what if your number range is used up? What do you do after have handed out XS999999 ? We cannot answer that for you .....

Inserting rows from one table to another another with PK column value incrementing in MS Access Database

We have two tables,table1(id int,name nvarchar(50)) and table2(id int,name nvarchar(50)). For both tables id is primary key.I want to move rows from table2 to table1 with PK value incrementing i.e i want id=max(id)+1 of table1 for all rows copying .I found this query like this for sql server
declare #root int
select #root=max(id) from Bgd_common.dbo.table1
insert into Bgd_common.dbo.table1(id,Name) select #root + ROW_NUMBER() OVER(ORDER BY ID),name from Bgd_common.dbo.table2
But ROW_NUMBER() will not work with Acces database.I don't want to use built in Auto increment property because I want to delete a row and then insert row in middle etc and Built in Auto increment property will cause some restriction on operations.How can i do same thing in MS access??
here is the link that would solve your problem
http://www.vb123.com/toolshed/07_access/countercolumn.htm
Is table1 ID an autonumber? If it is, you can simply copy table2 [name] to table1 and the values will increment. If it is not an autonumber, it may be best to make it one. MS Access works very well with autonumber IDs.
I used Dcount in place of Row Number() and it worked!
Here is final query
insert into Bgd_common.dbo.table1(id,Name) select (select max(id) from Bgd_common.dbo.table1) + Dcount("id","test2","id <= " & [id]) ,name from Bgd_common.dbo.table2

SQL Identity with leading padded zeros

I have marked a column as Identity in my table
create table Identitytest(
number int identity(1,001) not null,
value varchar(500)
)
I need the identity column to be incremented as 001,002,003, etc.
The database shows that it is inserting as 1,2,3, etc.
How can this be done?
As the others have already rightfully pointed out - an INT never has leading zeroes - it just holds the value, that's all (and that's good that way).
If you need some additional formatting, you could always add a computed column to your table, something like:
ALTER TABLE dbo.Identitytest
ADD DisplayNumber AS RIGHT('000' + CAST(number AS VARCHAR(3)) , 3) PERSISTED
This way, your INT IDENTITY will be used as an INT and always contains the numerical value, while DisplayNumber contains 001, 002, ... 014, 015, ..... and so forth - automagically, always up to date.
Since it's a persisted field, it's now part of your table, and you can query on it, and even put an index on it to make queries faster:
SELECT value FROM dbo.IdentityTest WHERE DisplayNumber = '024'
And of course, you could use just about any formatting in the definition of your computed column, so you could also add a prefix or something:
ALTER TABLE dbo.Identitytest
ADD DisplayNumber
AS 'ABC-' + RIGHT('000' + CAST(number AS VARCHAR(3)) , 3) PERSISTED
So in this case, your DisplayNumber would be ABC-001, ABC-002, ... and so on.
You get the best of both worlds - you keep your INT IDENTITY which is numerical and automatically increased by SQL Server, and you can define a display format any way you like and have that available at any time.
If you want to display your number column with leading zeros, just pad it in your SELECT statement. It's a number, it will NOT store with leading zeros as an integer.
SELECT RIGHT('00000' + CAST([number] AS varchar(5)) , 3)
FROM IdentityTest
The 3 is the number of characters you want total in the output display.
If you require both the auto-incrementing number (which can only be a number) and an alphabetic representation of the number, you might consider looking at computed columns.
Here's a few links to get you going:
http://www.mssqltips.com/tip.asp?tip=1682
http://msdn.microsoft.com/en-us/library/ms191250.aspx
http://www.kodyaz.com/articles/sql-server-computed-column-calculated-column-sample.aspx
Why do you need that? As an integer, 001 is the same as 1. If what you want is that for display or other purposes, create another column and do your work there (you may do it as part of a trigger on the table, on insert, that looks at the newly inserted row, and creates the entry in the column appropriately.
i've got a table where i'm storing an integer, but the users want to see it a XXX, even if it has zeroes, so i wrote this code
declare #a int
set #a=1
select replicate('0',3-len(#a))+ cast(#a as varchar(4))
Here is another method:
create table TEST_T (ui int NOT NULL identity, name varchar(10))
insert into TEST_T values ( 'FRED' )
select NAME, ui, RIGHT('0000' + LTRIM(STR(ui)), 4) as ui_T from TEST_T
go
/* NOTE: A view could be created with a calculated column instead of the identity column. */
create view TEST_V as select NAME, RIGHT('0000' + LTRIM(STR(ui)), 4) as ui_V from TEST_T go
go
select * from TEST_V
drop view TEST_V
drop table TEST_T
Not quite as much data duplication(?) as adding a column to the table and no need to specify the column in the select statement.
I need the identity column to be
incremented as 001,002,003, etc.
The database shows that it is
inserting as 1,2,3, etc.
SQL databases store values, not the literals you used to write those values. 002 is 2. Just like 1 + 1 is 2. Would you expect SELECT 1 + 1 to display the string "1 + 1" instead of 2?
If you want the leading zeros to be stored in your column, you have to use a character type. But then you can't use AUTOINCREMENT/IDENTITY.
What you probably really want is something like printf("%03d", number) in program that reads from the database.

Query regarding SQL Insert in SQL Server?

I am using SQL Server 2008 and developing a project which is in maintenance phase.
I want to insert record in a table whose primary key is an Integer but not an identity. e.g. table name is tblFiles and fields are ID, FileName, FileContent.
Actually that table is in use so I don’t want to make any schema change in it. And I want the key after row insertion because I have to put that in another table. Existing values in the Id column are different integer, means not in sequence.
So I want the query that also returns me the Id value. So I want to insert only FileName and FileContent and some sort of sql to whom I can embed in my insert query which insert a unique Id and also send me that id
Well, if it's not an IDENTITY field - don't you already have to specify the "ID" in your insert for it to succeed ? If so - you already have the ID! Or what am I missing? Is the ID determined by a trigger or something??
If so, try this query:
INSERT INTO dbo.tblFiles(FileName, FileContent)
OUTPUT inserted.ID
VALUES ('yourfile.name', 'your contents')
This should return the newly inserted ID from the INSERT query.
Marc
Change the Columns Identity Specification > Is Identity to Yes.
The after inserting into the table you can
Select SCOPE_IDENTITY()
to get the integer that was just added and return this in your SP.
If you really can't edit the database schema maybe you could add another table to the database that has two columns called ID and CurrentDate. Make the ID column an Identity. In your code insert into this table first select SCOPE_IDENTITY() and then use the integer returned to insert as the ID in your tblFles table.
P.S. Stop prefixing your table with tbl that's so 1999. :)
You could create a unique integer, not so elegantly, using
SELECT MAX(ID) + 1 FROM tblFiles
And simply return this from your query or sproc as the case maybe. Otherwise follow as marc_s says if it is known already.
UPDATE: have to say, rather than this fudge as requested, I would strongly recommend pushing back hard and getting table changed so this is an identity column, as this is what is. all answers so far are simply fudges, mine especially.
so my final query look like...
Insert into dbo.tblData (Id, FName, LName)
output inserted.Id
values ((SELECT MAX(ID) + 1 FROM dbo.tblData), 'xyz', 'abc')
We can assign max(ID)+1 in to an integer variable, then we can Insert
Declare #ID int
Select #ID = ISNULL(MAX(ID),0) + 1 FROM tblFiles
INSERT INTO tblFiles
(
ID, FileName, FileContent
)
Select #ID,'FileName','FileContent'
This insertion is direct,
INSERT INTO tblFiles
(
ID, FileName, FileContent
)
Select (Select ISNULL(MAX(ID),0) + 1 FROM tblFiles),'FileName','FileContent'
Here we have to use ISNULL condition because there is no data in table then it will return Null. So ISNULL(MAX(ID),0) + 1 this condition will give Data is null then 0+1=1.
Thank you