SQL Server 2012 :: How To Get Primary Key Value If Not Present In Foreign Key Via Join

May 4, 2014

I've following query which display the result as required, but I need to get the missing Primary Key Values which are not available in the result:

SELECTA.SignedByUserID, B.FullName, COUNT(A.OutletID) AS TotalSignups, DATENAME(Month, A.SignupDate) AS Month
FROMdbo.tblMer_Outlet AS A LEFT OUTER JOIN dbo.tblGen_Users AS B ON A.SignedByUserID = B.UserID
WHERE(A.SignupDate >= '2014-04-01 00:00:00' AND A.SignupDate <= '2014-04-30 23:59:59')
GROUP BY A.SignedByUserID, B.FullName, DATENAME(Month, A.SignupDate)

This Query returns the following result:

SignedByUserID FullName TotalSignups Month
--------------------------------------------------------
9 Babu Raj 16 April
11 Faheem 19 April
39 Fasil Abbas 16 April
29 Hafiz Suleman 10 April

[code]....

which does not have a signup for the month of April, but I need it to be available for this or any upcoming month. I need this orr all users, which does not exists in the context needs to be displayed in the result.

View 9 Replies


ADVERTISEMENT

SQL Server 2012 :: Insert Foreign Key Value Into Primary Table?

Oct 2, 2015

In a special request run, I need to update locker and lock tables in a sql server 2012 database, I have the following 2 table definitiions:

CREATE TABLE [dbo].[Locker](
[lockerID] [int] IDENTITY(1,1) NOT NULL,
[schoolID] [int] NOT NULL,
[number] [varchar](10) NOT NULL,
[lockID] [int] NULL
CONSTRAINT [PK_Locker] PRIMARY KEY NONCLUSTERED

[code]....

The locker table is the main table and the lock table is the secondary table. I need to add 500 new locker numbers that the user has given to me to place in the locker table and is uniquely defined by LockerID. I also need to add 500 new rows to the corresponding lock table that is uniquely defined in the lock table and identified by the lockid.

Since lockid is a key value in the lock table and is uniquely defined in the locker table, I would like to know how to update the lock table with the 500 new rows. I would then like to take value of lockid (from lock table for the 500 new rows that were created) and uniquely place those 500 lockids uniquely into the 500 rows that were created for the lock table.

I have sql that looks like the following so far:

declare @SchoolID int = 999
insert into test.dbo.Locker ( [schoolID], [number])
select distinct LKR.schoolID, A.lockerNumber
FROM [InputTable] A
JOIN test.dbo.School SCH ON A.schoolnumber = SCH.type and A.schoolnumber = @SchoolNumber
JOIN test.dbo.Locker LKR ON SCH.schoolID = LKR.schoolID
AND A.lockerNumber not in (select number from test.dbo.Locker where schoolID = @SchoolID)
order by LKR.schoolID, A.lockerNumber

I am not certain how to complete the rest of the task of placing lockerid uniquely into lock and locker tables?

View 7 Replies View Related

SQL 2012 :: Simple Way To Remember Primary And Foreign Key?

Dec 15, 2014

What is the simple way to remember Primary and foreign key?

Why is the ID column in a table declared as a integer datatype?

View 2 Replies View Related

Transact SQL :: 2012 / Insert Foreign Key Value Into Primary Table?

Oct 2, 2015

In a special request run, I need  to update locker and lock tables in a sql server 2012 database, I have the following 2 table definitions:

CREATE TABLE [dbo].[Locker](
 [lockerID] [int] IDENTITY(1,1) NOT NULL,
 [schoolID] [int] NOT NULL,
 [number] [varchar](10) NOT NULL, 
 [lockID] [int] NULL 
 CONSTRAINT [PK_Locker] PRIMARY KEY NONCLUSTERED

[Code] ....

The locker table is the main table and the lock table is the secondary table. I need to add 500 new locker numbers that the user has given to me to place in the locker table and is uniquely defined by LockerID. I also need to add 500 new rows to the corresponding lock table that is uniquely defined in the lock table and identified by the lockid.

Since lockid is a key value in the lock table and is uniquely defined in the locker table, I would like to know how to update the lock table with the 500 new rows.  I would then like to take  value of lockid (from lock table for the 500 new rows that were created) and uniquely place those 500 lockids uniquely into the 500 rows that were created for the lock table.

I have sql that looks like the following so far:

declare @SchoolID int = 999
insert into test.dbo.Locker ( [schoolID], [number])
select distinct LKR.schoolID, A.lockerNumber
 FROM [InputTable] A
JOIN test.dbo.School SCH ON A.schoolnumber = SCH.type and A.schoolnumber = @SchoolNumber
JOIN test.dbo.Locker LKR ON SCH.schoolID = LKR.schoolID
AND A.lockerNumber not in (select number from test.dbo.Locker where schoolID = @SchoolID)
order by LKR.schoolID,  A.lockerNumber

I am not certain how to complete the rest of the task of placing lockerid uniquely into lock and locker tables? Thus can you either modify the sql that I just listed above and/or come up with some new sql that will show me how to accomplish my goal?

View 7 Replies View Related

SQL 2012 :: Insert Data Onto Tables Having Primary And Foreign Key Relations?

Oct 31, 2015

Is there anyway to get the order in which data to be import on to tables when they have primary and Foreign Key relations?

For ex:We have around 170 tables and when tries to insert data it will throw error stating table25 data should be inserted first when we insert data in table 25 it say 70 like that.

View 3 Replies View Related

SQL Server 2012 :: How To Find Particular Table Is Present In Which Database

Jan 19, 2014

I have created a table but i forget in which database. I know the table name but i dont know the database name..

I have to filter my table from all database ... how can i do and find....

View 5 Replies View Related

SQL Server 2012 :: How To Delete Duplicate Rows Present In Parent Table

Oct 19, 2014

I have a master table and i need to import the rows into the parent and child table.

Master table name is Flatfile_Inventory
Parent Table name is INVENTORY
Child Tables name are INVENTORY_AMOUNT,INVENTORY_DETAILS,INVENTORY_VEHICLE,
Error details will be goes to LOG_INVENTORY_ERROR

I have 4 duplicate rows in the Flatfile_Inventory which i have already inserted in the Parent and child table.

Again when i run the query using stored procedure,its tells that all the 4 rows are duplicate and will move to the Log_Inventory_Error.

I need is if i have the duplicate rows in the flatfile_Inventory when i start inserting into the parent and child table the already inserted row have the unique ID i must identify it and delete that row in the both parent and chlid table.And latest row must get inserted into the Parent and child table from Flatfile_Inventory.

-- ===============================================================================================
-- STORED PROCEDURE FOR FLATFILE_INVENTORY
-- ===============================================================================================
USE [IconicMarketing]
---=======================================SALES_CURSUR===========================================
--USE IconicMarketing
--GO
DECLARE
@FileType varchar(50) ,
@ACDealerID varchar(50) ,

[code].....

View 2 Replies View Related

Reporting Services :: Copy Table From One To Another Server With Primary And Foreign Key Constraints

Jun 9, 2015

How to copy a table from one server to another server with primary and foreign key constraints.

View 5 Replies View Related

Join Between Two Tables Where Asset Tags Are Present

Dec 20, 2012

There are two tables A and B where asset tags are present, but in one table in rows and in another in column wise.

for eg
ASSet Tag
SR-062009-00032966
SR-062009-00032962
SR-072009-00020572
SR-072009-00020571
SR-072009-00020585
HH-092009-00038342

Table B
field 1 -->Asset TAG
Record 1-->SR-072009-00020572,SR-072009-00020571,SR-062009-00020685,SR-072009-00001592,SR-072009-00001376,SR-062009-00020683,SR-092009-00001617

field 2 --> Material code
REcord 1-->121
REcord 2-->123

What is the query so that asset tag of A matches with each and every asset tag table of B and output comes as

Output
Asset TAg -------- MAterial Code
SR-062009-00032966
SR-062009-00032962
SR-072009-00020572 ------121
SR-072009-00020571 -------121
SR-072009-00020585

View 5 Replies View Related

SQL Server 2012 :: Returning Value For Foreign Key

Dec 5, 2013

I have a table tbl_rules. This table will define rules for each role. I have not yet defined the fields for the rules. But the table definition is as below:

Create table tbl_Rules
(
ID int identity(1,1) not null,
Role_ID int not null,
primary key (ID),
constraint fk_RoleName foreign key (Role_ID)
references tbl_Role(ID)
)

The table tbl_role has two columns as below:

ID RoleName
1 Manager
2 Analyst
3 Admin

So far so good. I created the tbl_rules.

But what i want to do is when I do select * from tbl_Rules, i want to show as below:

ID Role_ID
1 Manager
2 Admin

Instead it shows:

ID Role_ID
1 1
2 3

Is there a way to do this? The goal is to return the select * from tbl_Rules results to a gridview to enable adds and changes. I could do this by doing queries for each column, but I was hoping to make it easier. Not sure if this is even possible.

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

SQL Server 2012 :: Foreign Key References Multiple Tables

Feb 12, 2014

Is there any possibility to create a foreign key references more than one tables.

say for example,
Create table sample1(id int primary key)
Create table sample2(id int primary key)

Create table sample3(
id int primary key,
CONSTRAINT fk1 FOREIGN KEY REFERENCES sample1 (ID),CONSTRAINT fk1 FOREIGN KEY REFERENCES sample2 (ID))

this shows no error while creating, but in the data insertion it shows error..

View 8 Replies View Related

SQL Server 2012 :: Efficient Way To Insert From Foreign Key Lookups

Feb 17, 2015

An SSIS task imports data from a flat file and inserts the data into a staging table. The staging table holds the data in its raw form. A second process then selects the data from the staging table, looking up the foreign key id's for raw data values, and then inserts the data into the live table.

SQL - Only key columns shown for clarity
-- Staging Table
CREATE TABLE Staging
(Information VARCHAR(10),
MachineName VARCHAR(10),
Status VARCHAR(10))

[code]...

The insert into the live table should look up the id for machine 1, and the id of status success and insert the foreign key values into the live table for the row.There could be 1000's of rows for the output of machine 1 all with different status's - (all pre set in the Status table, i.e success, failure, rerun) and the same for lots of other machines held in the machine table.

What is the best to insert this data all in one go, rather than reading each row of the staging table one by one, looking up the foreign key values depending on the machine and status values, then inserting the data.

I was thinking along the lines of:

INSERT INTO dbo.LiveTable
(Information, MachineID, StatusId)
SELECT Staging.Information, dbo.Machine.MachineId, dbo.Status.StatusId
FROM dbo.Staging
JOIN Machine ON Machine.MachineName = Staging.MachineName
JOIN STATUS ON Status.Status = Staging.Status But I notice the problem with this is, it doubles up the inserts!

View 2 Replies View Related

Transact SQL :: Size Of Foreign Keys In Server 2012?

Jun 30, 2015

I have question about the size of foreign key’s in sql-server 2012. If I in one table had a foreign key of the “INT” type. Do it still cost 4 bytes of storage?

View 6 Replies View Related

Foreign And Primary Key Question

Apr 24, 2007

OK - I have a two tables in a database. Table one contains an ID, 'oneID', field as the primary key. It is auto-incremented. Table two has ID field, 'twoID', as the primary key. This field also auto-increments. Table two also has 'oneID' as the foreign key.
Now, my question is, how do I get the foreign key in table two to auto-increment in conjuction with table one's primary key? They are after all the same data. Do I have to manually code to get table one data and save it to table two data?
thanks

View 1 Replies View Related

Clustered Primary Key And Foreign Key: T-SQL

Jun 10, 2005

I am having a little trouble getting this to work right, but have come a ways since I started this.......other tables created first and with no problems..... then these two with the last table being the problemI need to set one foreign key in the second table referencing the first table.But, the primary key is clustered with the two foreign keys and I get the error....There are no primary or candidate keys in the referenced table 'courseScores' that match the referencing column list in the foreign key 'FK_course'.CREATE TABLE dbo.courseScores   (     courseId varchar(20) NOT NULL    CONSTRAINT FK_courseId_courseStructure2 FOREIGN KEY (courseId)    REFERENCES courseStructure (courseId), 
    studentId varchar(20) NOT NULL    CONSTRAINT FK_studentId_students2 FOREIGN KEY (studentId)    REFERENCES students (studentId), 
    CONSTRAINT PK_courseScore PRIMARY KEY CLUSTERED (courseId, studentId)
          )CREATE TABLE dbo.objScores  (  tmp int IDENTITY(1,1) PRIMARY KEY,    objective varchar(50) NOT NULL,        courseId varchar(20) NOT NULL    CONSTRAINT FK_course FOREIGN KEY (courseId)    REFERENCES courseScores  (courseId)                  )
Once I get it working, then the tmp will be gone and then set 3 foreign keys as the clustered primary, fyi.Not sure how to reference half a primary key?Any help is greatly appreciated.....Thanks all,Zath

View 4 Replies View Related

Can A Column Act As Both Primary Key And Foreign Key?

Sep 11, 2011

Can a column act as both primary key and foreign key, if so what is script.

And can a table have more than one primary keys/foreign keys, if so what is the script.

View 4 Replies View Related

Foreign Key Value Has No Matching Primary Key

Sep 15, 2014

I'm currently using Oracle and receiving this error:

SQL Error: ORA-02291: integrity constraint (43437001.ATHLETE_FK1) violated - parent key not found
02291. 00000 - "integrity constraint (%s.%s) violated - parent key not found"
*Cause: A foreign key value has no matching primary key value.
*Action: Delete the foreign key or add a matching primary key.

When inserting this value:

INSERT INTO ATHLETE VALUES ('A001','TOM','HANKS','03-FEB-90','USA','C001');

With Tables:

CREATE TABLE ATHLETE(
ATHLETEID CHAR(4),
ATHLETEFIRSTNAME VARCHAR2(20),
ATHLETELASTNAME VARCHAR(20),
ATHLETEDOB DATE,
REPCOUNTRY VARCHAR2(12),

[Code] ......

I think the error is to do with the Athletes table (primary/foreign key)

How would I fix this in order to insert values without error?

View 3 Replies View Related

Foreign And Primary Keys

Oct 19, 2005

I have an application in which i need to get the foreign key fieldsfrom a table and then get all the foreign keys primary key field fromthe linking table. Could some one tell me how i do this usingINFORMATION_SCHEMA. I have tried and can get the foreign keys but notsure how to get the associated primary keys.

View 1 Replies View Related

Composite Primary Key And Foreign Key

Feb 8, 2008



Hi,
In my table1, I have a composite primary key ssn+firstname+lastname.
In table2 I have ssn, firstname, lastname, col1. In table2 I want to create a foreign key which references table1 primary key?
table1 and table2 has the primary, foreign key relationships. Still table2 need primary key. In table2 Can I make the ssn+Firstname+Lastname as primary key? or one column id as auto increment?

Which is best way?

Thanks

View 27 Replies View Related

Primary Key/foreign Key Relationship

May 11, 2007

I'm using MS SQL Server Studio Express 9.0. When selecting SQL Server Compact Edition, I'm able to create tables and primary keys with no problem. But how do I create a relationship with another table (foreign key)?

Bob K.

View 11 Replies View Related

SQL Server 2014 :: 2 Tables Combined Left Join To Primary Key Of A 3 Third Table

Sep 1, 2014

Looking to improve performance of the following code.

It basically generates future days for each dog. So there is a dog table and a day table with every day.

These 2 table cross join and then fill in missing rows. As time moves i will fill in further future dates but will need the initial insert to be a reasonable query.

All columns are covered by index's but the queries at the end take quite a long time. I would hope for index scan to just point out the missing rows especially on the final query.

How to make the last query as fast as possible.

IF OBJECT_ID('dbo.[AllDates]', 'U') IS NOT NULL
DROP TABLE dbo.[AllDates]
CREATE TABLE dbo.[AllDates] (
[Date] date not null PRIMARY KEY
)
;WITH Dates AS

[Code] .....

View 2 Replies View Related

Getting Information Dependant Upon Primary && Foreign Key

Aug 11, 2006

Hi All,
It seems I have been requested to carry out a complex query and the best way I think I can do this is with the use of a stored procedure. The problem is that I am not quite sure whether my SP is stated correctly and also how I would go about stating the SP in my VB.net code!
 
I would be ever so grateful if somebody could look over my SP code and possibly recommend a way of stating my code. My ability is limited so I would appreciate it if examples could be used with possible relations to my problem.
 
The Problem?
 
Tables:
 
1.tblRisk: Ref(pk), subject, status(fk), staff(fk), Dept(fk)
 
2.tblDept: Ref(pk), Department
 
The SP should state that Department should appear as the end result of the query when the page is loaded. So when a row is selected in tblRisk, dependant upon what the Dept is in that table, it then populates the department in which it is associated with from tblDept. I have left the SP below.  
 
Many Thanks,
Kunal   
 
CREATE PROCEDURE dbo.ShowMe @yourInputValue INTAS  SELECT tblDept.Department    FROM tblDept    JOIN tblRisk      ON tblDept.Ref = tblRisk.Dept  WHERE tblDept.Ref = @yourInputValue RETURN 0GO

View 1 Replies View Related

Foreign Key Constraint To A Composite Primary Key

Mar 6, 2008

I have two tables: table 1 and table 2. The primary key of table is composite key of two collumns and table 2 is the child of parent table 1. Is it possible to create / define a foreign key constraint using a composite primary key?

View 10 Replies View Related

Delete Data Which Is A Primary And Foreign Key

May 26, 2008

Hi,
How do I delete data which is a Foreign Key in another table?
For example;
string query = "DELETE * from user_details WHERE user_ID = '" +userID.Text+ "';
The user_ID is the Primary Key in the user_details table and also a Foreign Key in other tables.
Thank you. (:

View 4 Replies View Related

Dropping Primary And Foreign Keys

Jun 22, 2001

I am having trouble dropping constraints(Primary and Foreign Keys). I would like to do so so I can truncate the tables and repopulate them. Any time I use the DROP CONSTRAINT #### on one table, I get an error message saying this is referenced in another table. Any help in how to drop the keys so I can truncate the tables in a database would be appreciated. I must be overlooking something simple. Thanks for the help.

Regards,
Mark

View 2 Replies View Related

Composite Primary Key And Foreign Key - Relations

Sep 19, 2000

Hi,

I have a doubt, can anyone please clarify me.

I have created the following table,

create table z
(
eno int,
deptno char(2),
ename varchar(5),
constraint pk_eno_deptno primary Key(eno,deptno)
)
and I tried to establish a foreign key based on the above defined table. It's giving error,

create table z_dup
(
eno int FOREIGN KEY REFERENCES z(eno),
deptno char(2)
)
go

Error:-
*****
There are no primary or candidate keys in the referenced table 'z' that match the referencing column list in the foreign key 'FK__z_dup__eno__18CE1BA6'.Could not create constraint. See previous errors.

Even I tried to create a foreign key like the following,

create table z_dup
(
eno int FOREIGN KEY REFERENCES z(eno,deptno),
deptno char(2)
)
go

Error:-
********
More than one key specified in column level FOREIGN KEY constraint, table 'z_dup'.


Can anyone please help me to create a foreign key relation with the base table.

tks in advance,
Srinivasan

View 5 Replies View Related

Primary Key And Foreign Key Relation..URGENT!!!

Mar 11, 1999

Hi,

I have two tables.
CREATE TABLE Service(
SERVId varchar (10) NOT NULL,
SERVName varchar (30) NOT NULL,
SERVDesc TEXT NULL,
PRIMARY KEY(SERVId)
)



CREATE TABLE New(
SERVId varchar (10) NOT NULL,
NDId varchar (10) NOT NULL,
NDName varchar (30) NOT NULL,
NDDesc text NULL,
PRIMARY KEY(SERVId,NDId)
FOREIGN KEY(SERVId)
REFERENCES Service(SERVId)
)


Msg 547, Level 16, State 2
DELETE statement conflicted with COLUMN REFERENCE constraint 'FK__Newdev__SERVId__4939E6D2'. The conflict occurred in database 'test', table 'New', column 'SERVId'
Command has been aborted.


The same problem occurs even if the second table i.e. new is declared as follows, i.e created with only one primary key:
CREATE TABLE New(
SERVId varchar (10) NOT NULL,
NDId varchar (10) NOT NULL,
NDName varchar (30) NOT NULL,
NDDesc text NULL,
PRIMARY KEY(NDId)
FOREIGN KEY(SERVId)
REFERENCES Service(SERVId)
)


what might be the problem? But the same relation works on MS Access.
Is there anyother way of declaring this kind of relationship i.e. primary and foreign key?Can anyone pl. help me in solving this problem of foreign key relation.

thanks in advance
-chaitra

View 2 Replies View Related

Create Foreign Key Using Composite Primary Key

Jul 24, 2014

I am trying to create a FK using a composite PK and here are the details that I want to achieve.

Table -A
Column A1 not null,
Column A2 not null
Primary key (A1, A2).

Table -B
Column B1 Primary key.
Column B2 not null
FK (B2) References A(A1).

When I try to do this I am getting some errors. Questions: First of all is this possible? if yes, then how I can create it.

View 1 Replies View Related

Return Primary Key Even When Foreign Key Is Empty

Feb 20, 2015

I have a query that returns contacts connected to a client, but the problem is that it's only returning a result when a contact is associated with a client, even if the client does exist in the db. i want it to still return the client if the client exists.

SELECT * FROM clients, addressbook where clients.clientid = addressbook.clientid AND (clients.clientname LIKE '" . strtoupper($_GET['txtfname'])."%')

View 1 Replies View Related

Scripting Primary & Foreign Keys Only

Oct 28, 2004

Be warned, index padding is not included in this, and I'm not sure the fillfactor setting is correct.

set nocount on
create table #PK(constraint_schema sysname not null, constraint_name sysname not null, sql varchar(4000) not null, constraint PK_#PK primary key clustered(constraint_schema, constraint_name))
create table #cols(constraint_schema sysname not null, constraint_name sysname not null, column_name sysname not null, ordinal_position int not null, constraint PK_#PKcol primary key clustered(constraint_schema, constraint_name, ordinal_position))
create table #FK(constraint_schema sysname not null, constraint_name sysname not null,
unique_constraint_schema sysname not null, unique_constraint_name sysname not null,
sql varchar(4000) not null, constraint PK_#FK primary key clustered(constraint_schema, constraint_name))

insert into #PK
select constraint_schema, constraint_name, 'ALTER TABLE ' + quotename(table_schema) + '.' + quotename(TABLE_NAME) +
' ADD CONSTRAINT ' + quotename(CONSTRAINT_NAME) +
' PRIMARY KEY ' + CASE WHEN si.indid<>1 THEN 'NON' ELSE '' END +
'CLUSTERED (>cols<) WITH FILLFACTOR=' + cast(si.OrigFillFactor as varchar) + ' ON ' + quotename(fg.groupname)
AS SQL
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
INNER JOIN sysindexes si on TC.CONSTRAINT_NAME=si.name
inner join sysfilegroups fg on si.groupid=fg.groupid
WHERE CONSTRAINT_TYPE IN('PRIMARY KEY','UNIQUE')

insert into #fk
select c.constraint_schema, c.constraint_name, c.unique_constraint_schema, c.unique_constraint_name,
'ALTER TABLE ' + quotename(F.table_schema) + '.' + quotename(F.table_name) +
' ADD CONSTRAINT ' + quotename(F.constraint_name) +
' FOREIGN KEY(>cols<) REFERENCES ' + quotename(r.table_schema) + '.' + quotename(r.table_name) +
'(>rcols<)'
AS sql
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS F
INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C ON F.constraint_schema=C.constraint_schema AND f.constraint_name=c.constraint_name AND F.constraint_type='FOREIGN KEY'
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS R ON R.constraint_schema=C.unique_constraint_schema AND r.constraint_name=c.unique_constraint_name AND r.constraint_type in ('PRIMARY KEY','UNIQUE')
ORDER BY F.table_name, r.table_name

insert into #cols
select constraint_schema, constraint_name, COLUMN_NAME, ORDINAL_POSITION from INFORMATION_SCHEMA.KEY_COLUMN_USAGE

declare @ctr int, @max int, @delim varchar(1)
select @ctr=1, @max=max(ordinal_position), @delim='' from #cols

set nocount on
while @ctr<=@max
BEGIN

update P SET SQL=Replace(SQL, '>cols<', @delim + quotename(c.column_name) + '>cols<')
FROM #PK P INNER JOIN #cols C ON P.constraint_schema=C.constraint_schema AND P.constraint_name=C.constraint_name
WHERE C.ORDINAL_POSITION=@ctr

UPDATE F SET SQL=Replace(Replace(SQL, '>cols<', @delim + quotename(c.column_name) + '>cols<'), '>rcols<', @delim + quotename(r.column_name) + '>rcols<')
FROM #FK F INNER JOIN #cols C ON F.constraint_schema=C.constraint_schema AND F.constraint_name=C.constraint_name AND C.ordinal_position=@ctr
INNER JOIN #cols R ON F.unique_constraint_schema=R.constraint_schema AND F.unique_constraint_name=R.constraint_name AND C.ordinal_position=R.ordinal_position

select @ctr=@ctr+1, @delim=','
END
set nocount on

update #PK SET SQL=Replace(SQL, '>cols<', '')
update #FK SET SQL=Replace(Replace(SQL, '>cols<', ''), '>rcols<', '')

select sql from #PK
select sql from #FK

drop table #pk
drop table #fk
drop table #cols

View 5 Replies View Related

Can Only Use Primary Key And Not Foreign Key While Joining Tables?

Oct 9, 2015

I was trying a joining example provided in my book in which customer is a table and person is another table. The query provided in the book is this... USE AdventureWorks2012;

GO
SELECT c.CustomerID, c.PersonID, p.BusinessEntityID, p.LastName
FROM Sales.Customer AS c
INNER JOIN Person.Person AS p ON c.PersonID = p.BusinessEntityID;

This is the query that I did....

SELECT
      c.CustomerID,p.FirstName,p.MiddleName,p.LastName
FROM
      Sales.Customer AS c INNER JOIN Person.Person AS p
ON
      c.CustomerID=p.BusinessEntityID

ORDER BY
         p.BusinessEntityID;

Keys :-

Person Table
[PK_Person_BusinessEntityID]
[FK_Person_BusinessEntity_BusinessEntityID]

Customer Table
[PK_Customer_CustomerID]
[FK_Customer_Person_PersonID]

However,both of them gives a very different result set.But my question is why do we need to use the Customer.PersonID instead of Customer.CustomerID. Is it really important to use one primary key and one foreign,is there any specific reason why the book showed c.personId=p.BusinessEntityId.??

View 3 Replies View Related

List Primary And Foreign Keys

Jan 10, 2006

I have a DB with 100 tables. I was wondering if anybody knows a quick way to list primary and foreign key with the column name for all the tables.

Your help would make my life a lot easier

 

thanks

 

View 1 Replies View Related







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