Find Primary Key On Table.

Feb 26, 2008

I need to find the primary key of a table, in MySQL i used SHOW COLUMNS and looped through them to find which one was primary if any. The MSSQL equivalent is SELECT * FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = 'table_name' apparently. However the result doesnt give me any key information. How can i find out
1. if a primary key exists on a table
2. what column that primary key exists on

View 2 Replies


ADVERTISEMENT

T-SQL (SS2K8) :: Find Primary Key Table Name And Field Name Of Foreign Key

Apr 10, 2015

How can i find the primary field name and primary table name of a given foreign key.

For example

Table A:
IDa
Column1
Column2
Column3

Table B:
IDb
column1
column2
column3 <---- this is foreign key to table A's IDa

What i want to do is i pass input of tableB, column3 and i get name of Primary tableA and field name IDa. How is it possible to do in tsql ?

View 4 Replies View Related

How Do I Find Out What My Primary Key Is

Jun 9, 2008

in my database?

View 3 Replies View Related

How Do You Find A Primary Key Violation

Jan 11, 2005

I need to find out which record I am violating by trying to execute this stored procedure

ALTER PROCEDURE InsertCorovan2004
AS
INSERT INTO [GamingCommissiondb].[dbo].[Corovan_Table]
([TM #],
[FirstName],
[LastName],
[SS #],
[TerminationDate],
[Voluntary or Involuntary])

SELECT [TM #], FirstName, LastName, SocialSecurityNumber, TerminationDate, VoluntaryorInvoluntary
FROM dbo.TERMINATION
WHERE (TerminationDate BETWEEN CONVERT(DATETIME, '2004-01-31 00:00:00', 102) AND CONVERT(DATETIME, '2004-12-31 00:00:00', 102))

GO



when I execute it I get this error message
Server: Msg 2627, Level 14, State 1, Procedure InsertCorovan2004, Line 3
Violation of PRIMARY KEY constraint 'PK_Corovan_Table'. Cannot insert duplicate key in object 'Corovan_Table'.
The statement has been terminated.
Stored Procedure: GamingCommissiondb.dbo.InsertCorovan2004
Return Code = -4


I am trying to insert 2004 terms into the corovan table from TERMINATION table. How do you find out what records match from each table (compare the tables reocords for dups). How would I do this in the query analyzer since thats mainly what I use. I get a better understanding of how to create proceudure in the query analyzer so I;d rather stick to it.

In short I need to find the Culprit record that is preventing me from insert the 2004 records


Thank you

View 14 Replies View Related

Using SQL To Find Primary Keys

Jul 20, 2005

What query do I use to list the primary key for each user table, i.e.TABLE | PRIMARY_KEY |Regards,Alan*** Sent via Developersdex http://www.developersdex.com ***Don't just participate in USENET...get rewarded for it!

View 4 Replies View Related

A Query To Find Primary Key

Sep 4, 2007

I have a query that can tell me the columns in a table. In this case "Contact". What I would like to add to my query is if the column is part of the primary key. Can that be done? how so?




Code Snippet
SELECT
c.name AS column_name,
c.column_id,
SCHEMA_NAME(t.schema_id) AS type_schema,
t.name AS type_name,
t.is_user_defined,
t.is_assembly_type,
c.max_length,
c.precision,
c.scale
FROM
sys.columns AS c
JOIN sys.types AS t ON
c.user_type_id=t.user_type_id
WHERE c.object_id = OBJECT_ID('Contact') ORDER BY c.column_id;






Thnx
Matt

View 4 Replies View Related

Trying To Find Non Identity Primary Keys

Jan 26, 2006

This ain't working

SELECT T.TABLE_NAME,C.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLES T
JOIN INFORMATION_SCHEMA.COLUMNS C
ON T.TABLE_NAME = C.TABLE_NAME
WHERE OBJECTPROPERTY(OBJECT_ID(T.TABLE_NAME),
'TableHasIdentity') = 0
AND T.TABLE_TYPE = 'BASE TABLE'
AND OBJECTPROPERTY(OBJECT_ID(C.COLUMN_NAME),'IsPrimary Key') = 1
ORDER BY T.TABLE_NAME,C.COLUMN_NAME

This is giving me bogus results...

SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE OBJECTPROPERTY(OBJECT_ID(COLUMN_NAME),'IsPrimaryKe y') = 1

I have PK's all over the place. What gives? Too many cocktails with lunch?

View 1 Replies View Related

Trying To Find Tabes Without Primary Keys

May 29, 2008

I wrote a query that when run, will give me a listing of all tables in a database, and whether or not those table have primary keys.

Here's the query:




Code Snippet
select so.name, si.name from sysobjects so
left outer JOIN sysindexes si on so.id = si.id
where si.status = '2066' and so.type = 'u'
order by so.name asc


It works for the most part save for one small (big) problem. It gives me a list of tables that have a corresponding primary key, but doesn't list those without one. For example, in one database I run this query. I know for a fact that there are 26 tables in this database, and my query returns 16 rows (one for each table with a PK). I'd like to see those as well as those without one, with a NULL in the NAME column for the PK.

I've tried every join combo under the sun and still can't get the desired results.

Any insight would be appreciated!

Thanks!

View 11 Replies View Related

Script: Find Tables Without Primary Keys

Aug 3, 2002

...got tired of looking at them by hand.

Cheers
-b

DECLARE @vcDB varchar(20),@vcSchema varchar(20),@vcTable varchar(200)

Select @vcDB='mydb',@vcSchema='dbo'

DECLARE cLoop cursor for
select TABLE_NAME
from INFORMATION_SCHEMA.TABLES
where TABLE_CATALOG=@vcDB
and TABLE_SCHEMA=@vcSchema
order by TABLE_NAME ASC

open cLoop

FETCH NEXT FROM cLoop INTO @vcTable
WHILE @@FETCH_STATUS=0
BEGIN
if not exists (SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_SCHEMA = @vcSchema
AND TABLE_NAME = @vcTable
AND CONSTRAINT_TYPE = 'PRIMARY KEY')
print @vcTable + ' does not have a primary key'

FETCH NEXT FROM cLoop INTO @vcTable
END
Close cLoop
DEALLOCATE cLoop

View 2 Replies View Related

How To Find All Tables That Have An Identity Column As A Primary Key

Mar 6, 2008

How do i find all the tables that have an Identity Column as a primary key in a database. Thanks.

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

Transact SQL :: Find Column ADRSCODE Used In Indexes Or Primary Keys?

Oct 12, 2015

I wanted to find all occurrences of ADRSCODE in a Database where ADRSCODE is in either an Index or a Primary Key.

I know how to get all of the occurences of ADRSCODE in a database and the table associated with it, I just want to tack on the Index and/or primary key.

SELECTOBJECT_NAME(object_id)FROMsys.columns
WHEREname
='foo'

How can I get the other bit of information ?

View 2 Replies View Related

How To Find Missing Records From Tables Involving Composite Primary Keys

Nov 23, 2006

Table 1







     Code
    Quarter

500002
26

500002
27

500002
28

500002
28.5

500002
29

 

Table 2







     Code
           Qtr

500002
26

500002
27

 

I have these two identical tables with the columns CODE & Qtr being COMPOSITE PRIMARY KEYS

Can anybody help me with how to compare the two tables to find the records not present in Table 2

That is i need this result







    Code
   Quarter

500002
28

500002
28.5

500002
29

I have come up with this solution

select scrip_cd,Qtr,scrip_cd+Qtr from Table1 where
scrip_cd+Qtr not in (select scrip_cd+qtr as 'con' from Table2)

i need to know if there is some other way of doing the same

Thanks in Advance

Jacx

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

SQL Server 2012 :: Find Queries That Lock Tables Or Not Using Primary Key While Running Update

Jul 20, 2015

I need to search for such SPs in my database in which the queries for update a table contains where clause which uses non primary key while updating rows in table.

If employee table have empId as primary key and an Update query is using empName in where clause to update employee record then such SP should be listed. so there would be hundreds of tables with their primary key and thousands of SPs in a database. How can I find them where the "where" clause is using some other column than its primary key.

If there is any other hint or query to identify such queries that lock tables, I only found the above few queries that are not using primary key in where clause.

View 2 Replies View Related

Problem: Find All Table Names In Db And Then Find

Jun 12, 2008

I have 3 database say
db1
db2
db3

I need to setup a script to read all the table names in the database above and then query the database to find the list of Stored Procedure using each table.(SQL Server)

View 5 Replies View Related

Query Based Off Primary Key Of Parent Table - Adding Child Table

Jan 28, 2012

I need to add a child table that will tell us who the participants counselor is, what I did was I did a Make Table query based off the primary key of the Parent table and made that the link (foreign key) for the People_tbl and the Counselor_tbl, so if the counselor changes then the user adds the record to the counselor tbl and then puts in the Effective date. The problem is that when I run a report it doesn't show the present counselor always shows the old counselor?

Code:
SELECT Student_ind.StudentFirstName, Student_ind.StudentLastName, Student_ind.[Student ID], People_tbl.[Family ID], People_tbl.FirstName,
People_tbl.LastName, People_tbl.[Parent ID]
FROM People_tbl RIGHT OUTER JOIN
Student_ind ON People_tbl.[Family ID] = Student_ind.[Family ID]
WHERE (People_tbl.LastName = @Enter_LastName) AND (People_tbl.FirstName = @Enter_FirstName)

View 5 Replies View Related

SQL Server Admin 2014 :: Few Record Loss In Table Primary Key Where Same Records Exists In Foreign Key Table?

Jun 21, 2015

Previously same records exists in table having primary key and table having foreign key . we have faced 7 records were lost from primary key table but same record exists in foreign key table.

View 3 Replies View Related

How To Create Index On Table Variable (Table Don't Have Primary Key)

Feb 26, 2008



Hi all,


my stored procedure have one table variable (@t_Replenishment_Rpt).I want to create an Index on this table variable.please advise any of them in this loop...
below is my table variable and I need to create 3 indexes on this...


DECLARE @t_Replenishment_Rpt TABLE
(
Item_Nbr varchar(25) NULL,
Item_Desc varchar(255) NULL,
Trx_Date datetime NULL,
Balance int NULL,
Trx_Type char(10) NULL,
Issue_Type char(10) NULL,
Location char(25) NULL,
Min_Stock int NULL,
Order_Qty int NULL,
Unit char(10) NULL,
Issue_Qty int NULL,
Vendor varchar(10) NULL,
WO_Nbr varchar(10) NULL,
Lead_Time int NULL,
PO_Nbr char(10) NULL,
PO_Status char(10) NULL,
Currency char(10) NULL,
Last_Cost money NULL,
Dept_No varchar(20) NULL,
MSDSNbr varchar(10) NULL,
VendorName varchar(50) NULL,
Reviewed varchar(20) NULL
)

I tryed all below senarios...it is giving error...


--Indexing the @t_Replenishment_Rpt table on the column Names Item Number, Vender , Department Number
--EXEC sp_executesql(CREATE UNIQUE CLUSTERED INDEX Replenishment_index ON @t_Replenishment_Rpt (Item_Nbr))
--CREATE UNIQUE CLUSTERED INDEX Idx1 ON @t_Replenishment_Rpt.Item_Nbr
INDEX_COL ( '@t_Replenishment_Rpt' , ind_Replenishment_id , Item_Nbr )
--EXEC sp_executesql('SELECT INDEXPROPERTY('+ '@t_Replenishment_Rpt' + ', ' + 'Item_Nbr' + ',' + 'IsPadIndex' + ')')
--EXEC sp_executesql(SELECT INDEXPROPERTY('@t_Replenishment_Rpt', 'Vendor','IsPadIndex'))
--EXEC sp_executesql(SELECT INDEXPROPERTY('@t_Replenishment_Rpt', 'Dept_No','IsPadIndex'))


View 3 Replies View Related

How Do I Copy / Insert A Primary Key Value Of One Table Into Another Table?

Dec 10, 2007

 

Hi i have set up  two very simple tables, I want a user to be able to create a basic account ( data stored in User_Profile  table with Id set as the Primery Key as Identity) I
want the user to be able to be able to return to their account at a later date
and then post multiple reviews of different bands they have seen at a later date.
I kept the tables in my example very simple so I could get my head
around the concept, but generally, I want to connect the Id (PK) value in
User_Profile table to the User_Id filed in the User_Review table,
so every review that user writes, will be connected directly to their Id.  

Any help you could give would be fantastic a i have no idea where to start!!!

  

User_Profile

Id   int,  ( as primary Identity Key)

Name

City

Country

 

I have a second table called User Reviews

 User_Revews

Revew_Id   int ,  ( as primary Identity Key)

User_Id  int, ( I want this to contain the Id value in
the User profile Table)

Review_Details

 

 

Thanks

 

Odxsigma

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

Table Primary Key(Varchar) Table Question

Jan 17, 2008

Hi,

I have a Users table that I use for membership. I am using username varchar(30) as the primary key for this table since username will always be unique.




The question I have is regarding how SQL Server actually stores data:

I see that when I add users, they are always stored alphabetically sorted on username.

I was expecting that all users will appear on the users table in the order they were added.

Example: I have 3 users (john, jonah, wilson). Now I added 4 user with username='bob'

If I execute select * from users, it returns me (bob, john, jonah, wilson). Look bob has become the first row of the table.


My question: Is Sql server moving 3 older rows to make room for 'bob' and it is also rebuilding part of the index due this new username 'bob'?


If this is the case, then it will have big impact if I have 100K users and I add one user that becomes firstrow. In that case 99,999 rows will have to move.


Bottom line, insert, delete will be very expensive.

I know sql server keeps data physically sorted on PK. But I am concerned here since rows are losing the order in which they were inserted.

Thanks

View 8 Replies View Related

SQL Server 2012 :: Join To Find All Records From One Table That Do Not Exist In Other Table

Apr 29, 2014

I have table 'stores' that has 3 columns (storeid, article, doc), I have a second table 'allstores' that has 3 columns(storeid(always 'ALL'), article, doc). The stores table's storeid column will have a stores id, then will have multiple articles, and docs. The 'allstores' table will have 'all' in the store for every article and doc combination. This table is like the master lookup table for all possible article and doc combinations. The 'stores' table will have the actual article and doc per storeid.

What I am wanting to pull is all article, doc combinations that exist in the 'allstores' table, but do not exist in the 'stores' table, per storeid. So if the article/doc combination exists in the 'allstores' table and in the 'stores' table for storeid of 50 does not use that combination, but store 51 does, I want the output of storeid 50, and what combination does not exist for that storeid. I will try this example:

'allstores' 'Stores'
storeid doc article storeid doc article
ALL 0010 001 101 0010 001
ALL 0010 002 101 0010 002
ALL 0011 001 102 0011 002
ALL 0011 002

So I want the query to pull the one from 'allstores' that does not exist in 'stores' which in this case would the 3rd record "ALL 0011 001".

View 7 Replies View Related

Primary Key Per Table

Dec 2, 2013

There is a restriction that we must have only one primary key per table. We can have composite primary key by defining primary key over 2 or more columns. Actually,, a primary key uniquely defines the table and if we have two or more columns which follow unique and not null features why can't we have two primary keys?? I want to know what is the main reason behind having only one primary key in a table??

View 3 Replies View Related

What Happens If A Table Has No Primary Key?

Jul 23, 2005

I ran into a table that is used a lot. Well less than100,000 records. Maybe not a lot of records but i believethis table is used often. The table has 26 fields, 9 indexesbut no Primary Key at all!There are no table relationships defined in this database, noNatural keys, only Surrogate keys in the database.1- Maybe an odd question but is it normal to have 1/3 of thetable's fields as indexes? Is this a valid question or it reallydoesn't matter if you have 9 indexes if they are appropriate to beindexes?2- Below is the DDL of the indexes (Is DDL the appropriate termto describe the indexes?) Without going into too technical aboutwhat the table is, what relationships it has with other tables,would you be able to tell if the indexes are good, bad, too many,etc?3- If i open the table in DESIGN view in SQL EM, i don't seethe Primary key icon. Yet here i see the words "PRIMARY KEYNONCLUSTERED". Does this mean UNIQUENO is actually some typeof primary key? If it was CLUSTERED then SQL EM would showUNIQUEID with a key to the left it identifying it as a PK?If that is the case, then what is the difference betweenPRIMARY KEY NONCLUSTEREDandPRIMARY KEY CLUSTERED?CREATE UNIQUE CLUSTERED INDEX [TBLTEST_PK] ON[dbo].[TBLTEST]([UNIQUENO]) WITH FILLFACTOR = 80 ON [PRIMARY]GOCONSTRAINT [PK_TBLTEST] PRIMARY KEY NONCLUSTERED([UNIQUENO]) ON [PRIMARY]GOCREATE UNIQUE INDEX [ASSIGNUNIQUENAME] ON[dbo].[TBLTEST]([USERNO], [STARTDATE], [NAME]) WITHFILLFACTOR = 80 ON [PRIMARY]GOCREATE INDEX [ENDDATE] ON [dbo].[TBLTEST]([ENDDATE]) WITH FILLFACTOR = 80 ON [PRIMARY]GOCREATE UNIQUE INDEX [IUSERASSIGNACT] ON[dbo].[TBLTEST]([USERNO], [TASKNO], [PROCESSENTRYNO])WITH FILLFACTOR = 80 ON [PRIMARY]GOCREATE INDEX [STARTDATE] ON [dbo].[TBLTEST]([STARTDATE]) WITH FILLFACTOR = 80 ON [PRIMARY]GOCREATE INDEX [PROCESSENTRYNOTBLTEST] ON[dbo].[TBLTEST]([PROCESSENTRYNO]) WITHFILLFACTOR = 80 ON [PRIMARY]GO/****** The index created by the following statementis for internal use only. ******//****** It is not a real index but exists asstatistics only. ******/if (@@microsoftversion > 0x07000000 )EXEC ('CREATE STATISTICS [Statistic_NAME] ON[dbo].[TBLTEST] ([NAME]) ')GOCREATE INDEX [TASKNO_IDX] ON [dbo].[TBLTEST]([TASKNO]) WITH FILLFACTOR = 80 ON [PRIMARY]GOCREATE INDEX [TBLTEST_ORGANIZATIONNO_IDX] ON[dbo].[TBLTEST]([ORGANIZATIONNO]) WITHFILLFACTOR = 80 ON [PRIMARY]GOCREATE INDEX [TASKNOUSERNO] ON [dbo].[TBLTEST]([USERNO], [TASKNO]) WITH FILLFACTOR = 80 ON [PRIMARY]GOThank you

View 4 Replies View Related

Primary Key Of Table

Mar 21, 2008

Hi to all.

I have a table with about 8 columns as a primary key. I would like to delete one column but not destroy the other 7 primary keys and their relationships between the other tables. Is it possible to do this?

Thanks.

View 5 Replies View Related

Finding The Primary Key Of A Table.

Dec 3, 2007

I'm trying to find the primary key on a given table in SQL Server 2000 using SQL.  I'm querying the sysobjects table to find a given table, and then querying the sysindexes table.  I've ALMOST found what I'm looking for.   I see the indexes and columns etc. on the tables in the database, I just don't see the field that indicates that the index is the primary key.
Can anyone help?
Thanks, Alex

View 6 Replies View Related

The Dropped Table Does Not Have A Primary Key And Cannot Be Used

Feb 25, 2004

I'm trying to drop a table onto the design view in Web Matrix and the following message appears: "dropped table does not have a primary key and cannot be used".

I'm using a SQL 2000 database that was previously an MSDE 2000 database. Is there anyway that I can define a column as a primary key?

Thanks.

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

MS SQL Table Primary Key Increment

May 8, 2008

Hi Guys,

I have designed a simple table named "test" with ID as primary key and Name as a string data. When I delete a row from the table and insert a new row.. then the ID column increments itself by 1..
for eg : if i have 2 rows in my table

1 Karthik
2 you

if I delete the 2nd row and insert your name in the place of 2nd row..
actually my rows shows

1 Karthik
3 yourname

could anybody give me some advices..

Thanks,
Karthik Gopal

View 1 Replies View Related

One Primary Key To Two Column In Same Table

Feb 9, 2015

I have a table name Dispatch with the following column
ID,Date, Name, Pickup, Going

I have a next table called Move with the following column
ID, MoveName

I link Move table with Dispatch table via relationship.
ID_Pickup, ID_Going

upon running query no data is shown unless i remove one of the column form the query either pickup or going ...

View 7 Replies View Related

Creating Table With A Primary Key

Jun 29, 2006

Hi,

I need to create a new table in our database.
This table is not linked into the existing schema in anyway, so i'm not sure if I need a primary key or not.
either way, coudl anyone tell me how to create a primary key ni the CREATE TABLE statement.
I have tried searching but cannot find the answer.

many thanks,
Matt

View 7 Replies View Related

Update A Table With Primary Key

May 1, 2007

i have 2 tables. Table a and Table b. i need to insert only the new records from Table a to Table B

how do you update table B where the primary key is 4 columns.

solved.!

View 5 Replies View Related







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