Generate Unique Primary Key

Aug 17, 2007

Is there any way to auto generate the unique primary key when inserting data in MS SQL?
there is a way to create the increasing integer as primary key, but is there any ways other than that?

thank you

View 5 Replies


ADVERTISEMENT

Generate Unique Code Help

Nov 6, 2007

Hi Guys,

I am trying to insert a unique code, like a voucher code, into a table in MSSQL, 10 numbers (0-9) which obviously needs to be unique.

I can code this in ASP, but I think the process could be a bit long winded, i.e. create a key - run a stored procedure to see if it is free if not loop and check again. Surely there would be a way to do this in a stored procedure in one?

So the code would look like 3928492834.

1. Generate Key in SQL
2. Check if not used in column 'kcode' if it is, regenerate and check again.

Any advice would be greatly appreciated, I know how to do this in ASP but bit of a SQL newbie!

Thanks

John

View 2 Replies View Related

Generate Unique Numbers

May 1, 2008

Hi

Hi

I am using sqlserver 2005 and want to generate unique numbers for all the records in a table using sql.

Something like table A has


Code:

FRUITS
-------------
Oranges
Mangoes
Apricots
....

I want to write a sql query that does something like

SELECT convert(varchar(8),getdate(),12)+'000001' my_number,
fruits
from table A

so the output is


[code]
my_number Fruits
080501000001 Oranges
080501000002 Mangoes
080501000003 Apricots
[code]

is there a way to do this without resorting to identity columns

View 3 Replies View Related

How To Generate A Unique Barcode?

Jan 25, 2008

Hy all,

I'm working on a final project for school. It is a warehouse application. For this application I will need to generate a barcode. I have read some articles online and found out that I could use the code 39 barcode font.

I just don't fully understand how to generate the unique barcode. Could someone please help me? I also would like to store the barcodes in a sql server table. Could I use reports to print the barcode?

View 2 Replies View Related

Generate Unique Numbers For Each Record

May 1, 2008

Hi

I am using sqlserver 2005 and want to generate unique numbers for all the records in a table using sql.

Something like table A has



FRUITS
-------------
Oranges
Mangoes
Apricots
....



I want to write a sql query that does something like

SELECT convert(varchar(8),getdate(),12)+'000001' my_number,
fruits
from table A

so the output is


my_number Fruits
080501000001 Oranges
080501000002 Mangoes
080501000003 Apricots
....


regards
Hrishy

View 4 Replies View Related

SQL 2012 :: Generate Unique Values

Apr 23, 2014

I am working on an ASP.net web application which inserts new record into an underlying table.

It is actually a ConfirmationNumber and should be unique. I have used abs(checksum(newid()))

For this purpose. Is there a better way to accomplice this?

View 9 Replies View Related

T-SQL (SS2K8) :: Generate Unique String ID

Jun 30, 2015

I need to generate unique string Id from the range AAAAA to PZZZZ. This id will be unique for each Users for e.g.

User ---- TransactionNo ---- UniqueId
--------------------------------------------
12001 --- 101 --- AAAAA
12001 ---- 102 --- AAAAB
12001 --- 103 --- AAAAC
12001 ---- 104 --- AAAAD

13001 --- 105 --- AAAAA
13001 ---- 106 --- AAAAB
13001 --- 107 --- AAAAC
13001 ---- 108 --- AAAAD

more the records of each user, unique should be the ID as displayed above.. Optimized way to generate the same...

View 3 Replies View Related

Generate Random And Unique Number Within Sql ?

Dec 11, 2007

I need to generate a random 10 digit alphanumeric string that is also unique within a table. My application will be calling a stored procedure to insert this number into the table. This number will be associated with a id from another table. Is it better to generate the random number within sql (and perform the lookup at the same time), then just pass the number back to the calling application ?

If the calling application generates the number, it will also need to make a call to check if its unique. So im thinking it would be best to simply have sql generate this random number, check the number against the table and then insert the new record.

thoughts ?

View 5 Replies View Related

How To Generate Random UNIQUE 13 Digit Number?

Aug 22, 2007

Hi

I have a sql procedure. I need to create UNIQUE random 13 digit number to use for barcode.

How do I generate 13 digit UNIQUE random in sql procedure?

Advance thanks

View 20 Replies View Related

Transact SQL :: Generate Unique Username From Data Columns

Oct 19, 2015

I am trying to achieve the below problem statement, however I am getting stuck at the looping part.

EX: We have three columns

First Name |  Last Name | Mothers Name

I want to generate the username field using above columns, so lets consider, I have following data

First Name |  Last Name | Mothers Name
a                    b                  cdef
a                    b                  cdfg
a                    b                  cdfj

Expected Usernames:

1: a.b
2: a.b.c
3. a.b.cd

Basically, it has to be FirstName.LastName.(incremental letters from MothersName until the name becomes unique)

View 4 Replies View Related

How Can I Add A Unique Key Column To A Table And Generate Its Values Automatically?

May 2, 2006

Hi, all,

I have a question about adding a unique key column to an existing table.

what i trying to do is that: I have already created a table, now i wanna add a ID column to this table, and generate the values for ID column from 1 to the existing row number. How can I get this done?

Thanks a lot in advance for any guidance.

View 6 Replies View Related

Use Trigger To Generate Primary Key

Jan 27, 2004

I have create a recursive triggers in tblIncident. The PKID is the primary key in tblIncident, in this trigger, i'm trying to generate an auto increament primary key from the stored procedure GetMaxId and update to tblINcident, but I face a problem where PKID does not refresh the latest PKID, it always show the default value 0, until I requery the table. How to get the latest PKID?

/* Trigger in tblIncident */
CREATE TRIGGER GetPKID
ON tblIncident FOR
INSERT AS
DECLARE @PKID int
DECLARE @NEWVALUE int
DECLARE PKID_Cursor CURSOR FOR SELECT tblIncident.PKID FROM tblIncident, inserted
where tblIncident.PKID = Inserted.PKID
OPEN PKID_Cursor
BEGIN
FETCH NEXT FROM PKID_Cursor INTO @PKID

WHILE (@@fetch_status = 0)
BEGIN
SET @NEWVALUE = 0
/*Call stored procedure - getmaxid to get the latest PKID */
EXECUTE GetMaxId "IN", @NEWVALUE OUTPUT
Update tblIncident SET PKID = @NEWVALUE WHERE PKID = @PKID

FETCH NEXT FROM PKID_Cursor INTO @PKID
END
END

CLOSE PKID_Cursor
DEALLOCATE PKID_Cursor

View 5 Replies View Related

Using Identity To Generate A Primary Key

Jul 20, 2005

We are converting a legacy visual foxpro system to use a SQL back-end.A number of (existing DBF) tables currently have a zero-filled primarykey eg. '000255' which is just an auto-incrementing key - but alwaysstored as a char field with leading zeros.For backward compatibility we are considering retaining this primarykey and using an identity field to auto-generate the next value, thenconvert the new identity value into the new primary key. So ifidentity is 256 then the key field will be assigned '000256'.Now the problem with this is that the primary key must be non-null andunique so must be given a value in the INSERT statement. But, theidentity value isn't available (I presume) until after the INSERTstatement has executed.Is this a "don't go there" kind of problem?ThanksAndrew GrandisonSA Department of HealthAdelaide, South Australia

View 2 Replies View Related

SQL Server 2008 :: Generate 8 Char Alphanumeric Unique Sequence

Apr 20, 2015

GENERATE 8 CHARACTER ALPHANUMERIC SEQUENCES

Requirements
• ALPHANUMERIC FORMAT – > AA00AA00………..ZZ99ZZ99
Last 8 bytes will alternate between 2 byte alpha/2 byte numeric
• Generate from Alphabets – A through Z Numbers -0 to 9
• Generate Unique Sequence (No Duplicates).
• Must Eliminate letters I and O

Output Expected
• AA00AA00………..ZZ99ZZ99
• Using 24 alphabets & 10 digits ,
24*24*10*10*24*24 = 3 317 760 000 records

Below is my Sql Function -

CREATE function [dbo].[SequenceComplexNEW]
(
@Id BIGINT
)
Returns char(8)

[Code] .....

View 9 Replies View Related

How Do You Generate Primary Keys With SQL Server?

Oct 26, 2005

Hi,

The way i generate my primary keys is to keep a table

PrimaryKeyTable
PrimaryKeyName : varchar (name of the primary key, for example UserID)
PrimaryKeyID : int (the next key should have the number stored in that
field, if it was 12 then next time i add a row the UserID will be 12)

After adding a row, i increment the value of primaryKeyID.

Is there a way to let SQL server to handle the primary key? To let SQL generate the key himself instead of me?

Thanks,

View 4 Replies View Related

UNIQUE But Not PRIMARY

Oct 20, 2006

Hello
for MS SQL 2000 I want to CREATE a Table as follow :

CREATE TABLE [dbo].[Local] (
[id_Local] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar] (100) NOT NULL,
[Info] [nvarchar] (100) NULL
)


id_Local is PrimaryKey autoincrement
but Name must be UNIQUE (not 2 times the same name)

how can script it ?

thank you

View 2 Replies View Related

Primary Key Vs Unique Key

Aug 27, 2007

Hi,

Can anyone tell what are the specific scenarios where Unique key is recommened over primary key ?
While designing a database table in what all cases we should think about going for Unique key rather than a primary key.

Regards,
Amit

View 6 Replies View Related

Difference Between A Primary Key And A Unique Key?

Jan 19, 2008

 hello all sorry m asking Database Question .. m talking about SQL SERVER 2005  but i have bit confusion...  what difference between a
primary key and a unique key?  if m not wrong  then primary key doesn't allow NULLs, but
unique key allows  NULLs but in many searches comes that primary key doesn't allow NULLs, but
unique key allows one NULL only. what this means 'one NULL only'?? according to my practical we can give more then 1 nulls... plz clear this point???

View 1 Replies View Related

Ensuring Unique Primary Key

Jan 23, 2008



For our database application we get our primary keys by calling a stored procedure that pass's in the table name and outputs the next primary key number assigned to that table.



ALTER procedure [dbo].[sp_getNextKey]

@TableName char(100),

@NextKey T_ID output

as

SET TRANSACTION ISOLATION LEVEL READ COMMITTED

begin transaction

select @NextKey = NextKeyValue from T_KeyGenerator where TableName like @TableName

update T_KeyGenerator set NextKeyValue = NextKeyValue + 1 where TableName like @TableName

commit transaction


I then take that primary key, and other data, and insert that into the desired table.

The Problem I am having is that my user's keep getting "cannot insert duplicate key in table".
So I assume that I do not have the transaction set right, or missing something.
I need it to lock the row in the t_keyGenerator table so that no other users can view that row until I update it with the new value and commit the transaction.

Any help would be greatly appreciated

View 8 Replies View Related

UNIQUE/PRIMARY KEY Confusion.

Nov 9, 2006

I wrote this stored procedure and it works fine, it seems. The questions I have are as follows:
(1) What is the difference between PRIMARY KEY and UNIQUE. They seem to pertain to the same behavior. When I used only UNIQUE as qualifier I did not see that the column was marked as primary in the SQL Management Studio.
What I need is for a column to be unique in the sense that it would not allow duplicate values and it must have an INDEX on it. I need it to be descending.
(2) Did I do it right or there are aspects in here I do not quite see?

set ANSI_NULLS ON
set QUOTED_IDENTIFIER OFF
GO
ALTER PROCEDURE [dbo].[CreateTableDailyClose]
@symbol varchar (10) = null
AS
BEGIN
SET NOCOUNT ON;
DECLARE @SQL VARCHAR(500)
SET @SQL = 'CREATE TABLE dbo.dailyCl_' + @symbol + ' (
dateTimed DateTime NOT NULL PRIMARY KEY,
opened float NULL,
high float NULL,
low float NULL,
closed float NULL,
volume int NULL,
adjClosed float NULL
)'
EXEC sp_sqlexec @Sql
SET @SQL = 'CREATE UNIQUE INDEX dateTimed ON dbo.dailyCl_' +
@symbol + ' (dateTimed DESC) '
EXEC sp_sqlexec @Sql
END

Thanks.

View 16 Replies View Related

Unique Index On X Columns But Not Primary Key

Feb 23, 2006

my table :

CREATE TABLE [dbo].[users] (
[ID] [int] NOT NULL ,
[A1] [nvarchar] (100) NULL ,
[A2] [nvarchar] (100) NULL ,
[A3] [nvarchar] (100) NULL
) ON [PRIMARY]

i must keep ID columns as primary key

ALTER TABLE [dbo].[users] WITH NOCHECK ADD
CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED
(
[ID]
) ON [PRIMARY]


but now A1+A2 must be unique

how can i do it ?

thank you

View 5 Replies View Related

Question On Primary Key, Unique Index

Oct 8, 2007



Question: I have a test table like this


CREATE TABLE [dbo].[Test](
[name] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[addr] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
CONSTRAINT [PK_Test] PRIMARY KEY CLUSTERED
(
[name] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]


But when I tried to input my data like
'abc', '123 abc'
'abc ','123 abc'

SQL server won't recognize 'abc' and 'abc ' is a different value if the last character is a space. Is there a way to make it as a different value? I tried to drop the primary and input the data. When I ran a group by the name column, 'abc' show 2 instead of 1. Seems SQL server is trying to ignore the space at the end too.

I also noticed unique index have the same problem too. Please help.

View 5 Replies View Related

Transact SQL :: Need Of Primary Key If Everything Can Be Achieved By Unique Key?

Oct 13, 2015

What is the need of Primary Key if everything can be achieved by Unique Key? Everything that primary key does, Unique key can also fill those things.Why primary key is required?

View 4 Replies View Related

How To Return Primary Unique Index Key On Insert

May 27, 2002

Hi,

I am making a program in Visual Basic .NET with SQL Server 2000.

I have a table "MyTable" with a primary key named "Id". The primary key is 'Create Unique' checked and 'Index' selected. When I insert all the fields required, except "Id" of course, I need the new record's "Id" in my VisualBasic program, but I don't know how...

I must do one of them, but don't know how either of them:

-Create a trigger on insertion that will send to the user that sended the insert command the "Id" of the record just created.

or

-get the command in Visual Basic that will send the Insert command with a return field ("Id")

Thanks in advance,
Sebastien Anselmo

View 6 Replies View Related

Unique Colm Indexes And Primary Keys

Jan 25, 2006

I have a deal table, each of these investments must be unique. I created a int pk : idDeal. Does that make sense or should i just use the deal colm being it has a unique constraint,
Reguarding indexes, should i make the auto # colm my pk and make that the clustered index? and put another index on the Deal Colmn? Any suggestions welcomed

Thank you

View 4 Replies View Related

Lookup Primary Key Of A Master Table Which Is Does Not Contains Unique Key

Mar 21, 2008



Hi
I have a strange requirement in ETL operation. My Source contains only the details table data. Out of it, I have to load the master table and refer the Master table primary key ID to load Details table. I can easily load the Master Table with aggregate transformation. But problem is how to look up the Master Table Primary Key ID to load the Details table, as the master does not contains any unique key to lookup. This may seems to be strange but this is my requirement. You can refer the Source and Destination data model as below. They may give you clear picture. Can you guys help me out on this?

My Source Table
--------------------------








Citye Type
City Name

Source
New York

Via City1
Pittsburg

Destination City
Chicago

Source
New York

Via City1
Philadelphia

Destination City
Chicago


My Destination
------------------------






Master Table

ID

1

2









Detail Table



Master Table ID
Citye Type
City Name

1
Source
New York

1
Via City1
Pittsburg

1
Destination City
Chicago

2
Source
New York

2
Via City1
Philadelphia

2
Destination City
Chicago


Thanks

View 11 Replies View Related

Report Model - How To Create A Unique Logical Primary Key In A Named Query

Apr 7, 2008



Hi,
Te following situtation is :

ReportModel is created ,there is only a named query in DSV ,it has a few tables in it(The relationship are inner joins and outer joins).

The question is how could I create a unique logical primary key to identify each unique row in the named query dataset, and also you cannt generate a model unless the named query has a logical primary key . how can I solve this problem,any help?


View 2 Replies View Related

Generate Script For Primary Keys And Foreing Keys

May 16, 2008



Pls let me know How I generate script for All primary keys and foreign keys in a table. Thereafter that can be used to add primary keys and foreign keys in another databse with same structure.

Also how I script default and other constraints of a table?

View 2 Replies View Related

DB Engine :: How To Convert Unique Clustered Index Into Clustered Primary Key To Use With Change Tracking

Sep 4, 2015

We are going to use SQL Sever change tracking. The problem is that some of our tables, which are to be tracked, have no primary keys. There are only unique clustered indexes. The question is what is the best way to turn on change tracking for these tables in our circumstances.

View 4 Replies View Related

Composite Primary Keys Versus Composite Unique Indexes

Feb 20, 2007

Hello,

I have a table which has a composite primary key consisting of four columns, one of them being a datetime called Day.

The nice thing afaik with this composite key is that it prevents duplicate entries in the table for any given day. But the problem is probably two-fold

1. multiple columns need to be used for joins and I think this might degrade performance?
2. in client applications such as asp.net these primary keys must be sent in the query string and the query string becomes long and a little bit unmanagable.

A possible solutions I'm thinking of is dropping the existing primary key and creating a new identity column and a composite unique index on the columns from the existing composite key.

I would like to have some tips, recommendations and alternatives for what I should do in this case.

View 1 Replies View Related

T-SQL (SS2K8) :: Convert Non-cluster Primary Key To Cluster Unique

Nov 6, 2014

I have following script which i am planning to run to drop all non-clustered primary keys on a database and then created as clustered. I am using someone else's script so don't know how to modify this. Some of primary key columns are used in references in other tables.

is there anyway i can drop the existing primary keys and using their original script then create again as clustered including restoring all foreign and reference keys and unique or no unique.

DECLARE @table NVARCHAR(512), @tablename NVARCHAR(512),
@sql NVARCHAR(MAX), @sql2 NVARCHAR(MAX), @sql3 NVARCHAR(MAX),
@column NVARCHAR(MAX);
DECLARE @indexname NVARCHAR(512);
SELECT name As 'Table'

[Code] ....

View 8 Replies View Related

SQL Server 2012 :: Failing On Update With Unique Index Error (Not Unique)

Jul 5, 2015

This index is not unique

ix_report_history_creative_id

Msg 2601, Level 14, State 1, Procedure DFP_report_load, Line 161
Cannot insert duplicate key row in object 'dbo.DFP_Reports_History' with unique index 'ix_report_history_creative_id'.

The duplicate key value is (40736326382, 1, 2015-07-03, 67618862, 355324).
Msg 3621, Level 0, State 0, Procedure DFP_report_load, Line 161

The statement has been terminated.

Exception in Task: Cannot insert duplicate key row in object 'dbo.DFP_Reports_History' with unique index 'ix_report_history_creative_id'. The duplicate key value is (40736326382, 1, 2015-07-03, 67618862, 355324).

The statement has been terminated.

View 6 Replies View Related

What Is The Difference Between A UNIQUE INDEX And A UNIQUE CONSTRAINT?

Sep 22, 2004

A UNIQUE INDEX must inherently impose a unique constraint and a UNIQUE CONSTRAINT is most likely implemented via a UNIQUE INDEX. So what is the difference? When you create in Enterprise Manager you must select one or the other.

View 8 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved