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
ADVERTISEMENT
Jun 9, 2008
in my database?
View 3 Replies
View Related
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
View Related
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
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
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
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
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
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
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
Apr 17, 2014
how to find all primary key columns & foreign key columns in all database tables?
View 1 Replies
View Related
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
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
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
Jul 25, 2006
Hey I want to get some data from some tables but I want every fieldexcept the primary key field returned. Is this possible?I.e SELECT * (except primary) FROM table1, table2, table3Any ideas??
View 2 Replies
View Related
Nov 27, 2007
I am trying to run an insert query off of a sql datasource and I am erroring out. My code and stored procedure as of now are listed below. You will notice the section of the stored procedure that is pulling the value for facility_ID (primary key). I have also tried to pull these and pass the parameter from a label, but that does not work, giving an error that the stored procedure expects the parameter @Facility_ID which was not supplied. One other odd thing is that stepping through the code, I watched the parameter count total 21, but when running the insert command, the insert parameter count shows 20. With the code below (my current project), I get an error that null values can not be entered for facility_ID. Please help. CODE: Dim myConnection As New Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("FacilitiesBuild").ConnectionString) 'open myconnection myConnection.Open() Dim myCommand As New Data.SqlClient.SqlCommand(SqlDataSourceFac.InsertCommand, myConnection) myCommand.CommandType = Data.CommandType.StoredProcedure myCommand.Parameters.Add("@Name", Data.SqlDbType.VarChar, 50).Value = CType(Me.DetailsView1.FindControl("Textbox5"), TextBox).Text myCommand.Parameters.Add("@Address1", Data.SqlDbType.VarChar, 40).Value = CType(Me.DetailsView1.FindControl("Textbox3"), TextBox).Text myCommand.Parameters.Add("@Address2", Data.SqlDbType.VarChar, 40).Value = CType(Me.DetailsView1.FindControl("Textbox4"), TextBox).Text myCommand.Parameters.Add("@State", Data.SqlDbType.VarChar, 2).Value = CType(Me.DetailsView1.FindControl("Textbox17"), TextBox).Text myCommand.Parameters.Add("@Zip", Data.SqlDbType.VarChar, 10).Value = CType(Me.DetailsView1.FindControl("Textbox6"), TextBox).Text myCommand.Parameters.Add("@Phone", Data.SqlDbType.VarChar, 14).Value = CType(Me.DetailsView1.FindControl("Textbox7"), TextBox).Text myCommand.Parameters.Add("@Admin_Name", Data.SqlDbType.VarChar, 40).Value = CType(Me.DetailsView1.FindControl("Textbox8"), TextBox).Text myCommand.Parameters.Add("@Comments", Data.SqlDbType.VarChar, 250).Value = CType(Me.DetailsView1.FindControl("Textbox10"), TextBox).Text myCommand.Parameters.Add("@Owner", Data.SqlDbType.Char, 1).Value = CType(Me.DetailsView1.FindControl("TypeOwnerInsert"), Label).Text myCommand.Parameters.Add("@Beds", Data.SqlDbType.Int).Value = CType(Me.DetailsView1.FindControl("BedsInsert"), Label).Text myCommand.Parameters.Add("@Population", Data.SqlDbType.NText).Value = CType(Me.DetailsView1.FindControl("PopulationInsert"), Label).Text myCommand.Parameters.Add("@Type_Facility", Data.SqlDbType.Char, 1).Value = CType(Me.DetailsView1.FindControl("TypeFacilityInsert"), Label).Text myCommand.Parameters.Add("@Type_Other", Data.SqlDbType.VarChar, 40).Value = CType(Me.DetailsView1.FindControl("TypeOtherInsert"), Label).Text myCommand.Parameters.Add("@Profit", Data.SqlDbType.Char, 1).Value = CType(Me.DetailsView1.FindControl("ProfitInsert"), Label).Text myCommand.Parameters.Add("@Religious", Data.SqlDbType.Char, 1).Value = CType(Me.DetailsView1.FindControl("ReligiousInsert"), Label).Text myCommand.Parameters.Add("@Licensed", Data.SqlDbType.Char, 1).Value = CType(Me.DetailsView1.FindControl("LicensedInsert"), Label).Text myCommand.Parameters.Add("@Active", Data.SqlDbType.Char, 1).Value = CType(Me.DetailsView1.FindControl("ActiveInsert"), Label).Text myCommand.Parameters.Add("@City_ID", Data.SqlDbType.Int).Value = CType(Me.DetailsView1.FindControl("InsertCityLabel"), Label).Text myCommand.Parameters.Add("@Agency_ID", Data.SqlDbType.Int).Value = CType(Me.DetailsView1.FindControl("InsertAgencyLabel"), Label).Text myCommand.Parameters.Add("@County", Data.SqlDbType.NVarChar, 3).Value = CType(Me.DetailsView1.FindControl("InsertCountyLabel"), Label).Text myCommand.Parameters.Add("@Facility_ID", Data.SqlDbType.VarChar, 6).Value = CType(Me.DetailsView1.FindControl("InsertFacilityLabel"), Label).Text If CType(Me.DetailsView1.FindControl("DropDownList1"), DropDownList).SelectedItem.Text = "Please Select One" Then MsgBox("You must select an agency") Else : SqlDataSourceFac.Insert() End If STORED PROCEDURE: ALTER PROCEDURE [dbo].[SP_OMBFacilityAddDOTNET] @Name varchar(50), @Address1 varchar(40), @Address2 varchar(40), @State varchar(2), @Zip varchar(10), @Phone varchar(14), @Admin_Name varchar(40), @Comments varchar(250), @Owner char(1), @Beds int, @Population numeric(10,0), @Type_Facility char(1), @Type_Other varchar(40), @Profit char(1), @Religious char(1), @Licensed char(1), @Active char(1), @City_ID int, @Agency_ID int, @County nvarchar(3)ASBEGINDECLARE @Facility_ID varchar(6) DECLARE @nextID varchar(3) /* get next facilityID */ SELECT @nextID = MAX(RIGHT(Facility_ID, LEN(Facility_ID)-(CHARINDEX('-', Facility_ID)))) + 1 From OMBFacility Where Agency_ID = @Agency_ID SELECT @Facility_ID = CAST(@Agency_ID AS varchar(2)) + '-' + RIGHT('000' + RTRIM(@nextID), 3) INSERT INTO [AIMS].[dbo].[OMBFacility] ([Name], [Address1], [Address2], [State], [Zip], [Phone], [Admin_Name], [Comments], [Owner], [Beds], [Population], [Type_Facility], [Type_Other], [Profit], [Religious], [Licensed], [Active], [City_ID], [Agency_ID], [County], [Facility_ID]) VALUES (@Name ,@Address1 ,@Address2 ,@State ,@Zip ,@Phone ,@Admin_Name ,@Comments ,@Owner ,@Beds ,@Population ,@Type_Facility ,@Type_Other ,@Profit ,@Religious ,@Licensed ,@Active ,@City_ID ,@Agency_ID ,@County ,@Facility_ID)END
View 11 Replies
View Related
Dec 19, 2001
My table consists of about 1.4 Million Records. The PK is a CHAR field and ranges in size from 3 - 25 characters. I need to pull a recordset using the LEFT function.
Example: SELECT blah WHERE LEFT(myPK, 8) = 'AIRBILLNU'
This query takes about 115927ms to run and the server is 100% CPU bound, it should only bring up 2 records. Seems like the index is not being used. I know the DB design is probably not the greatest, we probably should have had an INT PK and IX on the other field which is now the PK. I cannot do anything about that at this point.
Is there anything I can do to speed up this query.?
Thanks,Adrian
View 3 Replies
View Related
Apr 6, 2012
I'm trying to modify a specific row in a table.
$paper_id = 2A
$query = "UPDATE book SET paper_id='$paper_id', title='$title'";
I'm getting this error <<query failed: Duplicate entry '2A' for key 'PRIMARY'>>
Structure:
Column: paper_id
Type: Char
Length: 20
Deafult: None
View 5 Replies
View Related
May 14, 2012
I have a table with plant types and plant names. Certain plants are grouped on a custom field, currently called Field. I am trying to create a query that will give me a result set containing the primary order on Type, but need items with the same 'Field' value grouped by each other.For example, the following shows a standard query result with "order by Type", ie select * from plants order by Type
Code:
ID Type Name Field
1 Type1Name1(group1)
2 Type2Name2(group2) -group2
3 Type3Name3(group3)
4 Type4Name4(group4)
5 Type5Name5(group2) -group2
6 Type6Name6(group6)
But I want it to look like this, with fields of the same value located next to each other in the result set (but still initially ordered by Type)
Code:
1 Type1Name1(group1)
2 Type2Name2(group2) -group2
5 Type5Name5(group2) -group2
3 Type3Name3(group3)
4 Type4Name4(group4)
6 Type6Name6(group6)
View 7 Replies
View Related
Sep 18, 2015
I am writing a query to display the count of products when a month is the primary month (Month where large sales happened)..Please consider the following query..
With Member ProductRank as
Rank([Date Due].[Calendar].currentmember,TopCount([Date Due].[Calendar].[Month],1,[Measures].[Sales Amount]))
Member PrimaryProd as
Count(Filter([Product].[Product].[Product],[Measures].ProductRank=1))
Select PrimaryProd on 0, Order([Date Due].[Calendar].[Month],PrimaryProd,bdesc) on 1 from [Sales]
Output:
It runs for 13 seconds on my laptop. I have modified the query to get the results fast like With
Set MySet as TopCount([Date Due].[Calendar].[Month],1,[Measures].[Sales Amount])
Member ProductRank as
Rank([Date Due].[Calendar].currentmember,MySet)
Member PrimaryProd as
Count(Filter([Product].[Product].[Product],[Measures].ProductRank=1))
Select PrimaryProd on 0, Order([Date Due].[Calendar].[Month],PrimaryProd,Bdesc) on 1 from [Sales]
Output:
This query runs instantly and result is not the same. Am I missing something here?
View 2 Replies
View Related
Jul 23, 2005
I have a 1:1 relationship between tables and am finding that the parentis sometimes mising the child.How do I query for what is not there?TIA
View 4 Replies
View Related
Sep 19, 2006
Hello All,
We have an app that we do not have the source code for that is behaving badly. I'd like to find out what queries it is running in order to possibly fix the issue form the SQL server side of things. Anyone know what table/view I should select off of to find the queries that have been run recently?
Thanks in advance!
View 1 Replies
View Related
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
Jul 19, 2004
Hi
I am trying to find when a name has been entered more than once into 1 database table.
I'm currently doing something like this (can't remember exactly, not at work)
SELECT COUNT(*) AS Cnt, Name
FROM tblTable
GROUP BY Name
ORDER BY Cnt Desc
This brings back all the Names in the database and tells me which are duplicates but I want to just have the results of the duplicate values and not the single values.
Hope you can help.
Thanks
View 2 Replies
View Related
Jul 8, 2002
Hello,
We had 10 scheduled jobs, which run more then 1000 Stored Procedures. I want to map the flow of dependency in Stored Procedure. Like SP 100 is dependent on SP 10, and SP10 was dependent on SP1 in our processing. If SP10 fails, we have to rerun SP1, SP10 and SP100 from Query analyzer. I was looking for a query or method to do find out flow of dependency in Stored Procedure.
Regards,
Vnk.
View 3 Replies
View Related
Jul 8, 2002
Hello,
We had 10 scheduled jobs, which run more then 1000 Stored Procedures. I want to map the flow of dependency in Stored Procedure. Like SP 100 is dependent on SP 10, and SP10 was dependent on SP1 in our processing. If SP10 fails in job, we have to rerun SP1, SP10 and SP100 from Query analyzer. I was looking for a query or method to do find out flow of dependency in Stored Procedure.
Regards,
Vnk.
View 3 Replies
View Related
Jan 12, 2005
I have a table with several foreign key relationships. I am scripting with PHP and was wondering if anyone knows how to query the database to show the relationships that a table has. I have been using MySQL, but for a number of projects have to use MS SQL.
Any help will be greatly appreciated.
View 2 Replies
View Related
Mar 7, 2006
Hi
I need help in finding the query which will provide the following resultset from the below table..
Table :
create table product_stocks(product_id int , product_type varchar(20) , no_of_units int)
Data:
insert into product_stocks values(1,'A',30)
insert into product_stocks values(2,'A',70)
insert into product_stocks values(3,'A',60)
insert into product_stocks values(4,'A',40)
insert into product_stocks values(1,'B',90)
insert into product_stocks values(2,'B',60)
insert into product_stocks values(3,'B',70)
insert into product_stocks values(4,'B',40)
insert into product_stocks values(1,'C',40)
insert into product_stocks values(2,'C',50)
insert into product_stocks values(3,'C',80)
insert into product_stocks values(4,'C',90)
Result Set:
product_type product_id no_of_units
--------------- ------------- --------------
A 2 70
A 3 60
A 4 40
B 1 90
B 3 70
B 2 60
C 4 90
C 3 80
C 2 50
i.e The result set gives the top 3 products in each product_type based on the no_of_units.
thanks
View 14 Replies
View Related
Nov 13, 2013
If I run sample query below against an adventureworks database
where can I find query cost?
USE AdventureWorks;
GO
EXEC dbo.uspGetManagerEmployees 140;
Does estimated subtree cost for in the actual execution plan (when right click SELECT operator in the execution plan) is considered query cost?
View 3 Replies
View Related
Sep 4, 2014
I have a warehouse table but I don't know which query will update warehouse inside of information ? Thus, how to write a query list all query have include this warehouse table name in there ?
View 1 Replies
View Related
Jun 20, 2007
can anyone explain how this works:
USE NORTHWIND
GO
SELECT freight
FROM orders E1
WHERE (N =
(SELECT COUNT(DISTINCT (E2.freight))
FROM orders E2
WHERE E2.freight >= E1.freight))
replace N by a number. To find that Nth value from the table.
Ashley Rhodes
View 2 Replies
View Related
May 5, 2008
Say the table has a primary key, and the latest value on it is 100, then all the records on that table are deleted... If I INSERT new record, the key will be 101... Can I find out what the key is going to be before inserting a new record to the table?
View 7 Replies
View Related
Aug 16, 2007
I've been struggling with this one for quite some time now and would appreciate some help:-
I'm trying to get a list of schools that only has male students. the closest I have so far:-
SELECT Schools.SchoolName, FORUM_MEMBERS.M_SEX , COUNT(Schools.SchoolName) AS no_of_students
FROM Schools
INNER JOIN FORUM_MEMBERS ON (Schools.SchoolID = FORUM_MEMBERS.SchoolID)
WHERE (FORUM_MEMBERS.UserType=4)
GROUP BY Schools.SchoolName, FORUM_MEMBERS.M_SEX
ORDER BY Schools.SchoolName, FORUM_MEMBERS.M_SEX;
The result is a list of schools:-
SchoolName, M_SEX, no_of_students
school 1, Male, 11
school 1, Female, 20
school 2, Male, 8
school 2, Female, 1
school 3, Male, 12
school 4, Male, 14
school 5, Male, 8
school 5, Female, 1
But what I really need is schools with only male students:-
SchoolName, M_SEX, no_of_students
school 3, Male, 12
school 4, Male, 14
Many Thanks
View 7 Replies
View Related