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


ADVERTISEMENT

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

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 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

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

Transact SQL :: Set Unique Random Number

Dec 1, 2015

Lets say we have a table (tblProducts)

ID   Item             RandomNumber
-------------------------------------------
1    JEANS                      1234567
2    SHIRT                    72813550
3    HOOD                             Null
4    TROUSER               72191839
5    BLAZER                              0

I want to perform a query so that SQL should look for RandomNumber Values and set a Unique Random Number Where RandomNumber Value is Null or 0.So I have got a solution as one of the MSDN Member shared the below query

select id,item,RandomNumber=Case when RandomNumber=0 then (select floor(rand()*100000000-1))
when RandomNumber is null then (select floor(rand()*100000000-1))
else RandomNumber end from tblProducts

So, can you all confirm me, that performing this query ensures that if a Value is assigned to one of the Item in RandomNumber Column, that value will not be assignend to any other Item in RandoNumberColumn.

View 15 Replies View Related

Transact SQL :: Merge With Unique Identifier As PK

Jul 2, 2015

Using SQL Server 2014 i try to merge data from database [Susi] on server2 to database [Susi] on server1. Server2 is a linked server in server1. The PK of the table Core.tKontakte is uniqueidentifier with rowguidcol.

I wrote the following script and get error 206: "uniqueidentifier ist inkompatibel mit int".

    INSERT Core.tKontakte (KontaktID, AnredeID, Titel, Nachname)
    SELECT KontaktID, AnredeID, Titel, Nachname
    FROM [Susi].MSCMS.Core.tKontakte AS Client
    WHERE NOT EXISTS (SELECT KontaktID FROM Core.tKontakte AS Host WHERE Host.KontaktID = Client.KontaktID);

[Code] ....

View 8 Replies View Related

Transact SQL :: Unique Pairs Of Data?

Sep 23, 2015

In my table, I have some duplicate rows. I want to select only the unique value pairs.

So, the table/data look like this:

ColumnA  -- ColumnB
123  -- 234
234  -- 345
234  -- 345
345  -- 456

I want to create a select statement that will only return:

123  -- 234
234  -- 345
345  -- 456

In other words, the duplicate row i.e. the second 234 - 345 -- won't be included in the set my SELECT statement will return.

View 2 Replies View Related

Transact SQL :: Assign Unique Number To Records?

Nov 15, 2015

Lets say I have a table - tblProducts

View 4 Replies View Related

Transact SQL :: Efficient Way To Calculate Unique Values?

Jul 14, 2015

I have a data set as -

ID       Set Date          DB Date
100     Null                 07/01/15
100     07/05/15         07/02/15
100     07/10/15        07/08/15

I want to able to get 2 unique dates

1. 07/02/15 - As I want the DB date for ID - 100 when set date changed from a null value to non null value.

2. 07/08/15 - As I want the DB date for ID - 100 when a non null set date changes.

The table has such records for lot of different ID's.

View 29 Replies View Related

Transact SQL :: How To Get 8 Digit Unique Number In Server

May 19, 2015

How to Generate the Unique 8 Digit Number in SQL SERVER.And also am trying with below methods which is not working as expected.

Methode-1:
SELECT CONVERT(VARCHAR(5),GETDATE(),112) +CONVERT(VARCHAR,DATEPART(MS,GETDATE())) AS '8DigitUniqNum'

Methode-2:
DECLARE @UniqueID uniqueidentifier
SET @UniqueID = NEWID()
SELECT LEFT(@UniqueID,8) AS '8DigitUniqNum'

View 9 Replies View Related

Transact SQL :: Insert Unique Values Only Using MERGE

Jun 2, 2015

I'm trying to use merge data from a staging table to a production table. There are a lot of duplicate values for serverName and I only want to insert one instance where there are duplicates.

How I can adapt the code I have so far to achieve this?

MERGE tblServer AS TARGET
USING tblTemp AS SOURCE
ON (TARGET.serverName = SOURCE.serverName)

WHEN MATCHED THEN
UPDATE SET TARGET.serverName = SOURCE.serverName, TARGET.serverLocation = SOURCE.serverLocation

WHEN NOT MATCHED BY TARGET THEN
INSERT (serverName, serverLocation)
VALUES (SOURCE.serverName, SOURCE.serverLocation)

WHEN NOT MATCHED BY SOURCE THEN
DELETE;

View 3 Replies View Related

Transact SQL :: How To Find Combination Of Column - Row Unique

Mar 8, 2012

I have table with some columns with no primary key..

I have to find the combination of columns which may the row unique...

How to do that like microsoft...

View 14 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

Transact SQL :: UPDATE Statement Failing On Unique Key Constraint

Jul 9, 2015

I'm trying to update rows in a simple table that has a UNIQUE KEY CONSTRAINT defined on one of its columns. Here is the DDL for the table:

CREATE TABLE [dbo].[SEC_USER](
 [SEC_USER_ID] [int] IDENTITY(1,1) NOT NULL,
 [USER_CODE] [varchar](100) NOT NULL,
 [USER_NAME] [varchar](128) NOT NULL,
 [EMP_CODE] [varchar](6) NOT NULL,

[Code] ....

When trying to execute the UPDATE statement the query fails with a constraint violation error:

Violation of UNIQUE KEY constraint 'UQ__SEC_USER__A039F1EE62FE8444'. Cannot insert duplicate key in object 'dbo.SEC_USER'. The duplicate key value is (34337).

What has  me baffled is that I'm not doing any insert. Also, the value that it's referencing - 34337 - doesn't exist in the table at all. I'd rather not drop the constraint.

View 8 Replies View Related

Transact SQL :: Select Unique From Table If Specific Value Does Not Exists

Jul 31, 2015

I have a table that has for each shop a value that can change over time.For example

BK_POS 1 --> Segment A
BK_POS 1 --> Segment /

What I would like to achieve is to get all distinct Shops (BK_POS) from the table above, but if for that specific pos a row exists where the segment = "/" then I do not want to take this BK_POS in my select query.More concrete, the for example above I do not want to select BK_POS 1 because he has one row where the segment = "/".

View 3 Replies View Related

Transact SQL :: Create Unique ID Based On Existing Fields

Sep 1, 2015

I have the following table (Table does not have unique key id )

Last Name     First Name         DATE        Total-Chrg

Jaime               KRiSH           5/1/2015         -4150.66
Jaime               KRiSH           5/1/2015          1043.66
Jaime               KRiSH           5/1/2015          1043.66
Jaime               KRiSH           5/1/2015           4150.66
Jaime               KRiSH           5/3/2015           4150.66
Peter                Jason            5/1/2015           321.02
Peter                Jason            5/1/2015           321.02
Peter                Jason            5/23/2015         123.02

I want the results to be in following way

Uniq ID    Last Name    First Name          DATE         Total-Chrg

1                Jaime            KRiSH                 5/1/2015     -4150.66
2                Jaime            KRiSH                 5/1/2015     1043.66
2                Jaime            KRiSH                 5/1/2015     1043.66
3                Jaime            KRiSH                 5/1/2015      4150.66
4               Jaime             KRiSH                 5/3/2015      4150.66
5               Peter              Jason                5/1/2015       321.02
6               Peter              Jason                5/1/2015       321.02
7               Peter              Jason               5/23/2015     123.02

May be we may do by dense_rank or Row_Number, but I couldn't get the exact query to produce based on the above table values.  There are some duplicates in the table(which are not duplicates as per the Business). For those duplicated Unique ID should be same(Marked in Orange Color which are duplicates). 

View 4 Replies View Related

Transact SQL :: SELECT Unique Values In Single Column?

Jun 8, 2015

I have the following two tables...

tblServer
-serverID
-serverName
-serverLocation
tblSite
-siteID
-serverID
-siteName
-siteIpAddress

I need to write a select query that gets the values of all columns but only returns unique sites because some sites are load balanced across several servers and where this is the case I don't want the site to appear multiple times in the list.

View 4 Replies View Related

Transact SQL :: Update Unique Records Count For Subquery?

Sep 2, 2015

updating the # of Payer from below query to match with the # of rows for each payer record. See the Current and desired results below. The query is currently counting the # of rows for all payers together and updating 3 as # of payers. I need it to count # of rows for each payer like shown inDesired result below. It should be showing 1 for first payer and 2 for 2nd & 3rd based on # of times each payer is repeated..

SELECT b.FILING_IND, b.PYR_CD, b. PAYER_ID, b. PAYER_NAME,a.CLAIM_ICN,
(Select Count(*) From MMITCGTD.MMIT_CLAIM a, MMITCGTD.MMIT_TPL b , MMITCGTD.MMIT_ATTACHMENT_LINK c where a.CLAIM_ICN_NU =
c.CLAIM_ICN and b.TPL_TS = c.TPL_TS and a.CLAIM_TYPE_CD = 'X' 

[Code] ....

Current Result

FILING_IND
PYR_CD
PAYER_ID
PAYER_NAME
CLAIM_ICN
#_OF_PAYER

[code]....

View 4 Replies View Related

Transact SQL :: Creating A View Using DISTINCT And Not Getting Unique Results?

Sep 21, 2015

I am building a view to be used to drill down into a Lightswitch app I'm building and to drive this I want to use a view based off the selection of that value several other values will be given to the user to choose from related to the first selection. I've created a view using the following statement:

SELECT DISTINCT TOP (100) PERCENT ARSFamily, ARS_Index
FROM dbo.csr_standards_cmsars
ORDER BY ARSFamily

 but the results come back with ALL the records of the source table (509 rows) when there should have only been 29 rows returned (the appropriate number of families or unique groups).  The index is necessary to have Lightswitch use the view as a data source.what I'm doing wrong here?

View 2 Replies View Related

Transact SQL :: How To Compare Duplicate Rows Within A Unique Process

Nov 9, 2015

We write to a log file each time a job runs. We give each job a unique batchid. I want to compare the run times of each step/record between two batch ids: '20150101888' and '20150101777'. Column Mins in the number of minutes each step ran. I am having trouble comparing the rows that have generic process and stepname – Trans Switch in this example. A new process within a batchid starts with a 'XX', 'Load'.

So I want to compare CA's Trans to CA's Tran Switch and ER's Trans Switch to ER's, etc. There can be multiple Trans Switch per process. There should be the same number between each batch, but no guarantees that  something might change. Also, Trans Switch is not the record right after the new process (CA, ER) in production.

I have just made a very simplified example.

/**
Want to compare 20150101888 to 20150101777 and end up with this result set. Notice that the duplicate process/step within a process has the process (CA and ER in this example) and a sequential number added to it: 'CA Trans 1'. Need this to pull out the largest time differences.

Time difference, process, step, mins1, mins2, batchid1, batchid2
-6, CA, Load, 17, 23, 20150101888, 20150101777
0, CA Trans 1, Switch, 8, 8, 20150101888, 20150101777
-6, CA Trans 2, Switch, 9, 15, 20150101888, 20150101777
-4, ER, Load, 7, 11, 20150101888, 20150101777
-4, ER Trans 1, Switch, 7, 11, 20150101888, 20150101777

**/

[Code] ....

View 4 Replies View Related

Transact SQL :: Primary Key For A View?

Apr 30, 2015

I am wondering if there is such thing as primary key for a view? Assuming, that my view is based on a single table and it's just a subset of columns (some of them renamed) including PK of the table it's based on.

The reason for my question is this - we're using Reverse POCO generator which automatically generates C# Model class and Configuration file for our tables and views. For the view is lists all the columns as a key and therefore I obviously can not use normal way of updating that view. I posted that as an issue here [URL] .... but I am thinking there is no such thing as the "primary key" for a view.

The query used to generate the classes is extremely complex already but may be it can be modified to get the PK ?

SELECT [Extent1].[SchemaName],
[Extent1].[Name] AS TableName,
[Extent1].[TABLE_TYPE] AS TableType,
[UnionAll1].[Ordinal],
[UnionAll1].[Name] AS ColumnName,
[UnionAll1].[IsNullable],
[UnionAll1].[TypeName],
ISNULL([UnionAll1].[MaxLength],0) AS MaxLength,

[Code] ......

I made a quick Google search and found this [URL] ....

It sounds as an interesting idea to try although I am not sure it will work with POCO Generator. But I'm going to try it now anyway.

View 7 Replies View Related

Transact SQL :: Finding Unique Counts Based On Consecutive Days?

Jul 9, 2015

I have a scenario here where the data looks like -

ID        Date
100      07/01
100     07/02
100    07/03
100   08/01
100   08/02
100   08/15

Now I need to find out unique occurrences of ID - 100 ( where count = unique only if the occurrences are in consecutive days, gap of even 1 day causes it to be a different instance ) - SO with the above data I should have unique occurrences as 3.efficient way to calculate this ?

View 5 Replies View Related

Transact SQL :: Difference Between Index And Primary Key

Aug 10, 2015

What is the difference between the Index and the Primary Key?

View 14 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







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