Sequence Of Columns In Primary Key

Oct 17, 2005

I am currently undertaking a review of the primary keys in a SQL Server
2000 database with a view to improving performance of queries.

I have heard that, in the case of compound primary keys, it is
important to select the correct order for the columns within the key.
For instance, imagine a table called OrderLine which has primary key
columns as follows-

Ledger
OrderNumber
OrderLineNumber

The theory I have heard is that columns with the most distinct values
should come first. In this case, Ledger is likely to have a maximum of
6 distinct values, OrderNumber a maximum of 10 million and OrderLine up
to 99. Based on this supposition I believe the best order would be-

OrderNumber
OrderLineNumber
Ledger

I have performed a few rudimentary tests that appear to bear this out.
I was wondering if anyone else has tried something similar and if so
what was the result?


Thanks,

Ross

View 14 Replies


ADVERTISEMENT

Updating Tables In Sequence With Primary Key And Foreign Key Relations

Feb 7, 2007

Hi all,
       In my project i will have the  data in a collection of objects, I need to update series of tables with foreign key relations
       Right now my code looks like this
       foreach(object obj in Objects){
       int accountId=Account.Insert(obj.accountOpenDate,obj.accountName);//this will update the accounts table and returns account id which is a Identity column in Acccounts table
       int DebtId=Debt.Insert(accountd,obj.debtamount,obj.debtbalance); this will update the Debts table and returns DebtId
       ///series of tables like above but all the relevant data comes from obj and in the Insert Methods i am using stored procedures to Insert the data into table
       }
      The no of objects varies from 1000 to 1 milliion,, with this approach its taking more time to update all the data. Please let me know if any alternative procedure to handle this kind of scenario.
 
Thanks
Regards
Prasad.

View 2 Replies View Related

DB Design :: Define Automatic Sequence On A Table Primary Key Field?

Jun 13, 2015

I am designing a database. I want to define a automatic sequence  on a table primary key field. what is the best solution for it?

I know I can enable identity property for a field, but  it has some problems ( for example its seed jumps on restart and unsuccessful events)

I also can use some calculated sequences. for example I can calculate max of the filed values and after incrementing use it as key for new inserted record.

which one is better?

View 3 Replies View Related

Sequence Of Columns And Preformance

Jul 6, 2006

Hello,I am learning SQL Server and I would like to ask you a question. Couldyou tell me please if sequence of columns in a table has influence onperformance?Thank you very much/RAM/

View 3 Replies View Related

Dynamically Concatenating Multiple Columns In Sequence?

Oct 16, 2014

I have a requirement where in I have to concatenate the fields based on their sequence given in another table along with respect to their lengths.

eg..

Input 1:

Table A: (below are the fields and their respective values, not all fields will have values)

-----------
KSCHL - ZIC0 (KEY)
KOTABNR - 521 (KEY)
MATNR
KUNNR-->1234567890
LIFNR
VKORG-->a234
PRCTR
KUNRE-->4355325363
LIFRE-->88390234
PRODH
---------

Table BSadIt contains the same fields as in table A and will have sequence number in which the concatenation should happen. The length field(LEN) will have corresponding field lengths(pipe delimited) should be considered in concatenation)

---------
KSCHL - ZIC0 (KEY)
KOTABNR - 521 (KEY)
MATNR
KUNNR-->1
LIFNR
VKORG-->3
PRCTR
KUNRE-->2
LIFRE -->4
PRODH
LEN--> 10|10|4|10

Expected Result:

---------------------
KSCHL - ZIC0 (KEY)
KOTABNR - 521 (KEY)
MATNR
KUNNR1234567890
LIFNR
VKORGa234
PRCTR
KUNRE4355325363
LIFRE0088390234
PRODH
Concat_String12345678904355325363a2340088390234

Note: If the field length given in Table B doesn't match with actual size of the fields then, the field should be filled with 2 left spaces while concatenation.. Eg. In above example say LIFNR value = 88390234(len =icon_cool.gif

then after concat the value should be like below:

12345678904355325363a234 88390234

Note:The fields are not constant..I have around 40 fields like that in which any combination of fields can be possible...eg..

KSCHL - ZIC0 (KEY)
KOTABNR - 521 (KEY)
MATNR -->2
KUNNR--> 4
LIFNR
VKORG-->1
PRCTR
KUNRE
LIFRE --> 3
PRODH

I am not sure which field has the value 1, 2 etc.. and how many fields are forming the combination..It can be sometimes 3/40 fields or it can be 10/40 fields...I have to dynamically get those values and concat...

I can have any number of fields for concatenation..above example is just for 4...it should be dynamic enough to handle any number of fields..

View 2 Replies View Related

Updating Two Columns With Sequence Numbers With Where Clause?

Jun 29, 2015

I have a table which has two column like following table and I don't know how can I update theses two column with identity numbers but just the fields which are equal 111.

my example table:

numez numhx
111 111
111 111
0 111
111 0
111 0

and my results should be:

numez numhx
1 2
3 4
0 5
6 0
7 0

View 4 Replies View Related

SQL Server 2014 :: Dynamically Concatenating Multiple Columns In A Sequence?

Oct 16, 2014

I have a requirement where in I have to concatenate the fields based on their sequence given in another table along with respect to their lengths. eg..

Input 1:

Table A: (below are the fields and their respective values, not all fields will have values)
-----------
KSCHL - ZIC0 (KEY)
KOTABNR - 521 (KEY)
MATNR
KUNNR-->1234567890
LIFNR
VKORG-->a234
PRCTR
KUNRE-->4355325363
LIFRE-->88390234
PRODH

Table BIt contains the same fields as in table A and will have sequence number in which the concatenation should happen. The length field(LEN) will have corresponding field lengths(pipe delimited) should be considered in concatenation)

KSCHL - ZIC0 (KEY)
KOTABNR - 521 (KEY)
MATNR
KUNNR--> 1
LIFNR
VKORG-->3
PRCTR
KUNRE-->2
LIFRE -->4
PRODH
LEN10|10|4|10

Expected Result:
---------------------
KSCHL - ZIC0 (KEY)
KOTABNR - 521 (KEY)
MATNR
KUNNR1234567890
LIFNR
VKORGa234
PRCTR
KUNRE4355325363
LIFRE0088390234
PRODH
Concat_String12345678904355325363a2340088390234

Note: If the field length given in Table B doesn't match with actual size of the fields then, the field should be filled with 2 left spaces while concatenation.. Eg. In above example say LIFNR value = 88390234(len =icon_cool.gif then after concat the value should be like below:

12345678904355325363a234 88390234

Note:The fields are not constant..I have around 40 fields like that in which any combination of fields can be possible...eg..

KSCHL - ZIC0 (KEY)
KOTABNR - 521 (KEY)
MATNR -->2
KUNNR--> 4
LIFNR
VKORG-->1
PRCTR
KUNRE
LIFRE --> 3
PRODH

I am not sure which field has the value 1, 2 etc.. and how many fields are forming the combination..It can be sometimes 3/40 fields or it can be 10/40 fields...I have to dynamically get those values and concat...

I can have any number of fields for concatenation..above example is just for 4...it should be dynamic enough to handle any number of fields..

View 2 Replies View Related

Data Mining :: Updating Two Columns With Sequence Numbers With Where Clause

Jun 29, 2015

I have a question  in SQL server. For example I have a table which has two column like following table and I don't know how can I update theses two column with identity numbers but just the fields which are equal 111.

Example table:
numez numhx
111 111
111 111
0 111
111 0
111 0

and my results should be:
numez numhx
1 2
3 4
0 5
6 0
7 0

View 3 Replies View Related

Primary Key On 17 Columns

Dec 7, 2001

Hi Guys,
When I create a table with a composit primary key with 18columns. I get this error
"Cannot specify more than 16 column names for index key list. 17 specified."
I really have to have these columns as primary key.
Is there any workaround to create this table;
Thanks

View 3 Replies View Related

Primary Key On Two Columns

Apr 15, 2007

How can I create a primary key on two columns? I could not find any sensible code sample or description how it should be done. It is clear from MSDN that it is possible but there are no examples.



There is a textbox "Included Columns" in one of the tools for setting primary keys for one column but it does not allow me to enter anything.



Thanks.

View 3 Replies View Related

How To Retrieve Primary Key Columns From Db?

Jan 12, 2007

Hello all.  I need to extract the column names that form the primary key group on a table in SQL Server.  I have a table called Account and it contains ten columns.  The primary key consists of two columns  - MasterAccountID, AccountID.  This primary key is a unique constraint and is clustered (it acts as an index as well as a primary key group).  I have tried the following to no avail:exec sp_pkeys Account   -> returns no rowsexec sp_helpindex Account -> throws an error stating that the object 'Account' does not existIf I run the following SQL statement, I can see all of the PK_* constraints in the database, so I know they are there:select * from information_schema.table_constraintswhere constraInt_type IN ('PRIMARY KEY','FOREIGN KEY') Again, I need to be able to specify a table name and have it return the columns (don't care if it returns extra fields) that make up the primary key fields for that table.  Thanks!   

View 2 Replies View Related

How To Get Primary Key (Columns) Of A Table?

Jan 5, 2006

I want to get the Primary Key Columns in Arrays by sending a tablename. I am using SQL Server 2000 and I want to make a find utility in VB.net whichwill work for all the forms; I have tables with one Primary key and some tables with composite Primary keys. I used to do this in VB 6 by making a function which fills the Primary Keys inList Box (I require to fill in list box), now I need to get in array. Can some one tell me the migration of the following VB 6 Code? This was written for the MS Access, I need same for SQL Server, I cannot find Table Def and Index Object in VB.net 2003. Public Sub GetFieldsFromDatabase (ldbDatabase As Database, lsTableName AsString)     Dim lttabDef As TableDef  Dim liCounter As Integer  Dim liLoop As Integer  Dim idxLoop As Index  Dim fldLoop As Field
  With ldbDatabase    For Each lttabDef In .TableDefs      If lttabDef.Name = lsTableName Then        liCounter = lttabDef.Fields.Count        For liLoop = 0 To liCounter - 1          cboFieldLists.List(liLoop) = lttabDef.Fields(liLoop).Name        Next liLoop        For Each idxLoop In lttabDef.Indexes          With idxLoop            lblIndexName = .Name            If .Primary Then              liCounter = 0              For Each fldLoop In .Fields               cboPrimaryKeys.List(liCounter) = fldLoop.Name                liCounter = liCounter + 1              Next fldLoop            End If          End With        Next        cboFieldLists.ListIndex = 0        If cboPrimaryKeys.ListCount > 0 Then          cboPrimaryKeys.ListIndex = 0        End If        Exit For      End If     Next End WithEnd Sub

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

Delete Records When You Have A Primary Key Of Two Columns

Jun 12, 2006

Hi everyone.

I have two tables: the catalog table and the detail table.
The two tables are joined by a two-columns key.

I want to make a Delete sentence for delete all the rows in the Catalog table that aren't in the detail table, in SQL Server.

The only problem is that the key is composed by two colums.

If the Key was maded of one column, that would be easy, like this:

DELETE FROM CATALOG
WHERE CATALOGKEY NOT IN (SELECT CATALOGKEY FROM DETAIL)

But it is possible to make a delete sentence if the key has two columns ?


Thanks

View 2 Replies View Related

Primary Key Columns Issues In Replication

May 29, 2007

Hi ,
Plz help me.
The scenario is as follows
I have a db on sql server 2005.I have replicated the db on sql server 2000.All the data counts seems to be correct.But the online websites are not able to execute queries generating error(Microsoft OLE DB Provider for sql server error '80040e21'.Multiple step OLE DB operation generated errors.Check each OLE DB status value,if available.No work was done.)Same web aspcode is working for other db (which were replicated from sql server 2000).
Also one more thing that was observed is as follows:
1)Prmary key was replicated for some of the tables.When primary keys were removed manually report executed fine.

Thanks in advance
Satish

View 2 Replies View Related

SQL Server 2012 :: Primary Key And Identity Columns

May 23, 2015

Can a Primary Key column also be a Identity column? The reason I am asking this question is because I have created a table and each time I insert data into the Address Table I am also inserting the AddressID, how do I get the Primary Key (AddressID column) to self generate ID values.

View 9 Replies View Related

SQL Server 2012 :: Define Primary Key Based On 2 Columns?

Sep 24, 2014

I've two tables A, B. In A table, I need to define the primary key with combination of 2 columns and this Primary Key will be a foreign key in table B. Based on these PK and FK I'll be writing a join to get the second column in table B.

View 0 Replies View Related

How To Find All Primary And Foreign Key Columns In All Database Tables

Apr 17, 2014

how to find all primary key columns & foreign key columns in all database tables?

View 1 Replies View Related

Enter Default Values For All Columns In All Tables Except Primary Keys

Jul 23, 2005

How can i enter Default Values of " " to all the columns of type characterof all the tables (excluding system tables) and Default Values of 0of all columns of type numbers. Excluding all primary key columns.Thank you

View 1 Replies View Related

Delete Statement For A List Of Items With Multiple Columns Identifying Primary Key

Jul 7, 2006

I frequently have the problem where I have a list of items to delete ina temp table, such asProjectId Description------------- ----------------1 test12 test43 test34 test2And I want to delete all those items from another table.. What is thebest way to do that? If I use two IN clauses it will do it where itmatches anything in both, not the exact combination of the two. I can'tdo joins in a delete clause like an update, so how is this typicallyhandled?The only way I can see so far to get around it is to concatenate thecolumns like CAST(ProjectId as varchar) + '-' + Description and do anIN clause on that which is pretty nasty.Any better way?

View 2 Replies View Related

Reducing Storage Space By Moving Rarely Required Columns To Separate Table While Sharing Primary Key Constraint

Aug 17, 2006

Dear all,

In my current database design, there is one table (PState) which has a Primary Key (int) and a few other fields.

During development, a pattern started to arise; for certain rows in PState, I wanted to specify an additional set of columns (over 10 of them with quite large lengths) for each row in PState. However, as these additional columns would only be required in approximately 20% of the rows of PState, there would be plenty of NULL values in PState if I would make this table wider than necessary. So, I decided to create a separate table with those optional columns (PStateWFI). In order to attach these additional columns in PStateWFI to PState in the cases they were needed, I would obviously have to create a Foreign Key constraint on the Primary Key of PStateWFI so that these optional rows would know which row in PState they would belong to.

However, the problem with this approach is that one could define multiple rows in PStateWFI referring to the same row in PState, which would not make sense. Thus, a UNIQUE index constraint added to the constrained ID column in PStateWFI would make sense to ensure that there could only be one set of optional columns added to each row in PState. But now, when adding the UNIQUE index, the FK constraint started to appear as a bidirectional key link in the Diagram; hence, new entries in PState would have to meet a FK constraint based on PStateWFI, which was not intended.

Hence, I had to create a quite awkward design to enforce the constraints:

1. The PState table has a Primary Key (PState.ParticleID, int, Identity Specification: Yes)
2. The PStateWFI table has a Primary Key (PstateWFIID, int, Identity Specification: Yes)
3. PStateWFI has field "PStateID" which has a FK constraint to PState.ParticleID (which is a one-way constraint operating in the correct way and does not constrain insertions in PState)
4. PStateWFI has an additional column ParticleIDIndex which has a UNIQUE Index attached to it.
5. There is a check constraint on PStateWFI enforcing PStateWFI.ParticleIDIndex = PStateWFI.ParticleID.

Although this structure does the job, it makes it necessary to add a redundant column in PStateWFI by duplicating the PStateWFI.ParticleID into PStateWFI.ParticleIDIndex, since I can't create a UNIQUE index on PStateWFI.ParticleID without constraining the PState table as well. So, insertions into this table would have to insert the same value into two columns. Not a big deal, but appears slightly ugly.

Basically I'd hope someone could explain why a bidirectional FK constraint has to be enforced on the primary key table in a relationship when the constrained column in the primary key table has a UNIQUE index attached on it. I have a few other cases where the above approach would benefit from a more clear structure.

Thanks in advance for any advice.

View 6 Replies View Related

Creating Indexes On Columns That Are Foreign Keys To Primary Keys Of Other Tables

Jul 16, 2014

what the best practice is for creating indexes on columns that are foreign keys to the primary keys of other tables. For example:

[Schools] [Students]
---------------- -----------------
| SchoolId PK|<-. | StudentId PK|
| SchoolName | '--| SchoolId |
---------------- | StudentName |
-----------------

The foreign key above is as:

ALTER TABLE [Students] WITH CHECK ADD CONSTRAINT [FK_Students_Schools]
FOREIGN KEY([SchoolId]) REFERENCES [Schools] ([SchoolId])

What kind of index would ensure best performance for INSERTs/UPDATEs, so that SQL Server can most efficiently check the FK constraints? Would it be simply:

CREATE INDEX IX_Students_SchlId ON Students (SchoolId)
Or
CREATE INDEX IX_Students_SchlId ON Students (SchoolId, StudentId)

In other words, what's best practice for adding an index which best supports a Foreign Key constraint?

View 4 Replies View Related

Columns In Primary Table And Foreign Key Table

Feb 12, 2007

mahesh writes "HI,

I am new to sql server.

can anybody help me

I have a table named tblqualificationmaster.

can i know the foreignkeys and the table related to this

tblqualificationmaster having foeign keys using stored procedure."

View 1 Replies View Related

RS2k Issue: PDF Exporting Report With Hidden Columns, Stretches Visible Columns And Misplaces Columns On Spanned Page

Dec 13, 2007

Hello:

I am running into an issue with RS2k PDF export.

Case: Exporting Report to PDF/Printing/TIFF
Report: Contains 1 table with 19 Columns. 1 column is static, the other 18 are visible at the users descretion. Report when printed/exported to pdf spans 2 pages naturally, 16 on the first page, 3 on the second, and the column widths have been adjusted to provide a perfect page span .

User A elects to hide two of the columns, and show the rest. The report complies and the viewable version is perfect, the excel export is perfect.. the PDF export on the first page causes every fith column, starting with the last column that was hidden to be expanded to take up additional width. On the spanned page, it renders the first column on that page correctly, then there is a white space gap equal to the width of the hidden columns and then the rest of the cells show with the last column expanded to take up the same width that the original 2 columns were going to take up, plus its width.

We have tried several different settings to see if it helps this issue or makes it worse. So far cangrow/canshrink/keep together have made no impact. It is not possible to increase the page size due to limited page size selection availablility for the client. There are far too many combinations of what the user can elect to show or hide to put together different tables to show and hide on the same report to remove this effect.

Any help or suggestion on this issue would be appreciated

View 1 Replies View Related

Convert Composite Primary Key Into Simple Primary Key

Jan 11, 2007

Uma writes "Hi Dear,
I have A Table , Which Primary key consists of 6 columns.
total Number of Columns in the table are 16. Now i Want to Convert my Composite Primary key into simple primary key.there are already 2200 records in the table and no referential integrity (foriegn key ) exist.

may i convert Composite Primary key into simple primary key in thr table like this.



Thanks,
Uma"

View 1 Replies View Related

Adding Primary Key To A Table Which Has Already A Primary Key

Aug 28, 2002

Hi all,
Can anyone suggest me on Adding primary key to a table which has already a primary key.

Thanks,
Jeyam

View 9 Replies View Related

Auto Incremented Integer Primary Keys Vs Varchar Primary Keys

Aug 13, 2007

Hi,

I have recently been looking at a database and wondered if anyone can tell me what the advantages are supporting a unique collumn, which can essentially be seen as the primary key, with an identity seed integer primary key.

For example:

id [unique integer auto incremented primary key - not null],
ClientCode [unique index varchar - not null],
name [varchar null],
surname [varchar null]

isn't it just better to use ClientCode as the primary key straight of because when one references the above table, it can be done easier with the ClientCode since you dont have to do a lookup on the ClientCode everytime.

Regards
Mike

View 7 Replies View Related

SQL Server 2008 :: Change Primary Key Non-clustered To Primary Key Clustered

Feb 4, 2015

We have a table, which has one clustered index and one non clustered index(primary key). I want to drop the existing clustered index and make the primary key as clustered. Is there any easy way to do that. Will Drop_Existing support on this matter?

View 2 Replies View Related

Sequence No.

Feb 6, 2004

Hi,
How can I generate a sequence No. using a simple SELECT statement.

like

declare @key
set @key = 1

SELECT @key, e.name from Employee

Now I want to display name of the employee and Key value which should get incremented automatically for each employee..
Is there any way?
Please help me..

View 1 Replies View Related

Sql Sequence

Dec 18, 2007

hi

i've been asked to write a sql sequence for a database i'm building but i haven't been using SQL very long and i have no idea how to write a sequence. Does anyone know anything about sql sequences?

thanks

jessica

View 14 Replies View Related

Sequence

Jul 20, 2005

Hi,I need little help with Ms SQL Server 2000. I would like to know how tocreate sequence or something like that. I want to have an automatic counterfor each row in one entity, so then I can do something like this:INSERT INTO table VALUES (use sequence(something), value, value, .... )Can you please help me?thxTomas

View 1 Replies View Related

4 Key Primary Key Vs 1 Key 'artificial' Primary Key

Jan 28, 2004

Hi all

I have the following table

CREATE TABLE [dbo].[property_instance] (
[property_instance_id] [int] IDENTITY (1, 1) NOT NULL ,
[application_id] [int] NOT NULL ,
[owner_id] [nvarchar] (100) NOT NULL ,
[property_id] [int] NOT NULL ,
[owner_type_id] [int] NOT NULL ,
[property_value] [ntext] NOT NULL ,
[date_created] [datetime] NOT NULL ,
[date_modified] [datetime] NULL
)

I have created an 'artificial' primary key, property_instance_id. The 'true' primary key is application_id, owner_id, property_id and owner_type_id

In this specific instance
- property_instance_id will never be a foreign key into another table
- queries will generally use application_id, owner_id, property_id and owner_type_id in the WHERE clause when searching for a particular row
- Once inserted, none of the application_id, owner_id, property_id or owner_type_id columns will ever be modified

I generally like to create artificial primary keys whenever the primary key would otherwise consist of more than 2 columns.

What do people think the advantages and disadvantages of each technique are? Do you recommend I go with the existing model, or should I remove the artificial primary key column and just go with a 4 column primary key for this table?

Thanks Matt

View 5 Replies View Related

How To Add A Newline Sequence

Apr 9, 2007

I have a SQL 2005 stored procedure to generate an email when passed parameters such as receipient, subject etc
 One of the paramteres passed to it is @body which is the body text of the message.  I want to be able to add a couple of blank lines and then some footer information.  This is working right now except I can't find the right way to add newlines into the string within the store procedure, so my footer information just tags right on after the bodytext.
I have tried but that literally adds the two characters  and n
Can anyone advise how to generate newlien sequences in T-SQL.
Regards
Clive

View 1 Replies View Related







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