Concatenate value to generated unique ID - sql

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

Related

Microsoft SQL Server - Copy column in table, modify value and type

I'm quite new to scripts and need some help on creating a script doing multiple actions in sequence.
Let's use this tentative (and bisarre) table to illustrate the solution. The table could potentially hold hundreds of entries:
I want to add a PhoneNumber column with varchar type and populate it from the existing PhoneNumber column.
For phone numbers consiting of 5 digits I want to add a leading zero (0) so all entries have the same length (6).
When this is done for all occurances of 5-digit phone numbers I want to delete the old PhoneNumber column
This is how the table should look after step 1:
And after step 2 it should look like this:
Finally, after the third step I want this outcome:
Can this be accomplished with a script? I don't really need the script to follow this exact sequence as long as it results in the desired outcome. This is just the sequence of actions I have thought could be an allright approach.
Here you go
Remember, you can't have 2 columns called the same
ALTER TABLE [TABLENAME] ADD PHONENUMBERCHAR char(6); --Adds a new column
GO;
UPDATE [TABLENAME] SET PHONENUMBERCHAR = RIGHT(CONCAT('000000', PHONENUMBER), 6); --Updates the value
GO;
ALTER TABLE [TABLENAME] DROP COLUMN PHONENUMBER --Deletes the old column
If the value is really an integer, you can use format():
select id, phonenumber, format(phonenumber, '000000')
from t;
You may want to add this as a computed column:
alter table t add phonenumber_6 as (format(phonenumber, '000000'));

How can I update the value of a field in a table to be a random number that's unique most of the time?

I have a simple table:
CREATE TABLE [dbo].[Word] (
[WordId] INT IDENTITY (1, 1) NOT NULL,
[NameId] INT NOT NULL
PRIMARY KEY CLUSTERED ([WordId] ASC)
);
I have a unique index on NameId
I am trying to update this table and change one column to a random number:
UPDATE Word SET NameId = ROUND(RAND()*2147483647,0)
I realize there is a very very small chance this will not work but it's actually failing every time even though the table has only a very small number of rows the update always fails and says there's a duplicate.
Can anyone tell me what's happening here and also suggest a way to update this table so that there's no duplicate values of NameId created most of the time.
You are updating every NameId with same value, use WHERE statement to update only one row
EDIT: This should do the trick you are looking for, NewId() generates new id for each row
UPDATE Word SET NameId = abs(checksum(NewId()) % 2147483647)
How many rows do you have? It could be a case of the birthday paradox.
Have you tried doing this:
SELECT ROUND(RAND()*2147483647,0) FROM Word
Do the numbers really need to be pseudo-random? You could use row_number() to make them increment.

update rows one by one with max value + 1 in SQL

here is my situation,
I have 2 tables,
1st table has all records, and it has IDs
2nd table has new records and it doesnt have ID, yet.
I want to generate ID for 2nd table with max(id) + 1 from 1st table.
when i do this, it makes all rows same id number, but i want to make it unique increment number.
e.g
select max(id) from table1 then it gives '997040'
I want to make second table rows like;
id
997041
997042
997043
997044
i think i need to use cursor or whileloop, or both, but i could not create the actual query.
sorry about bad explanation, i am so confused now
Use ROWNUM to generate incrementing row numbers. E.g.:
SELECT someConstant + ROWNUM FROM source.
CREATE TABLE table_name
(
ID int IDENTITY(997041,1) PRIMARY KEY
)
I hope this sql query would work!!
Or refer http://www.w3schools.com/sql/sql_autoincrement.asp

How to generate auto generated sequence no in sql

I have one requirement. I already have a table named WorkOrder. In this table there is a column Named WorkorderId set as primary key and identity. The next one is voucherNumber. Now I want to generate voucherNumber automatically. The condition is voucher number will not repeat. E.g., first I insert 2 rows into the table and after that I delete the 2nd entry. The next time my voucher number should be 3. Again i insert 3 more entries then after that my voucher no should be 6. Then i delete one row from this table after that my voucher number should be 7. If i delete the last row (I mean 7) then next time the voucher number should the same.
Use IDENTITY(...) when creating the column. This will make a field auto-increment its value.
You'll have to drop the column first in case that it already exists. There is no (clean) way to make this happen on already existing columns.
For further information and examples you can check out http://www.w3schools.com/sql/sql_autoincrement.asp
Edit: Sorry, I have overlooked the info that you are already using IDENTITY(...) on the PK column. Unfortunately SQL-Server can only have a single column with the IDENTITY property per table... So in this case you'll have to make use of a trigger.
This is an example:
CREATE TRIGGER CountRows
ON TestCount
AFTER UPDATE
AS
UPDATE TestCount SET Cnt = Cnt +1 WHERE ID IN (SELECT ID from inserted)
GO
In case you want to enter an IDENTIFIER to the record, it is best to use uniqueIdentifier type column. It is a string constant in the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, in which each x is a hexadecimal digit in the range 0-9 or a-f. For example, 6F9619FF-8B86-D011-B42D-00C04FC964FF is a valid uniqueidentifier value.
On insertion, you can simply proceed as follows;
Insert into MyTable
(WorkorderId, WorkName) values (NewId(), 'Test')
Using this, you can be sure the Id is globally unique.

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?