Foreign key shows nulls (ssms) - sql

I am trying to do a very simple task - to connect two tables with a foreign key. However, after successful creating of the key, the column in the main table is full of NULL values.
I tried to create the relationship both with a script and using 'Design table' option.
So, I have two tables - Swimmer (Has 100000 rows)
CREATE TABLE [dbo].[Swimmer](
[SwimmerID] [int] IDENTITY(1,1) PRIMARY KEY NOT NULL,
[FirstName] [nvarchar](50) NOT NULL,
[LastName] [nvarchar](50) NOT NULL,
[PassportNumber] [nvarchar](20) ,
[BirthDate] [date] NOT NULL,
[Gender] [nvarchar](5) ,
[Rank] [nvarchar](10) ,
[CoachID] [int] )
And Coach (has 10000 rows):
[CoachID] [int] IDENTITY(1,1) PRIMARY KEY NOT NULL,
[FirstName] [varchar](50) NOT NULL,
[LastName] [varchar](50) NOT NULL,
[PassportNumber] [nvarchar](20) )
I want to connect them by CoachID, so the column CoachID in Swimmer becomes a foreign key that references the column CoachID in Coach, however when I do, the column CoachID in Swimmer just shows NULL in every row.
My next task will be to create a one-to-many relationship (since one coach can instruct multiple swimmers), but for now I just want to figure out why the connection is not working

Related

Multiple Foreign key with a same primary key

I am using Microsoft SQL Server 2014 Express as a database server.
I have the following two tables between which I want to create PK-FK relationship.
CREATE TABLE [dbo].[Account]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[ACCOUNTNAME] [nvarchar](max) NOT NULL,
[ACCOUNTTYPE] [int] NOT NULL,
[CREATE_TIMESTAMP] [datetime] NOT NULL,
[LAST_EDIT_TIMESTAMP] [datetime] NOT NULL,
[OPENING_BALANCE] [decimal](18, 2) NOT NULL DEFAULT ((0)),
[OPENING_BALANCE_TYPE] [nvarchar](50) NULL,
CONSTRAINT [PK_dbo.Account]
PRIMARY KEY CLUSTERED ([ID] ASC)
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
CREATE TABLE [dbo].[Voucher]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[VOUCHERTYPE] [nvarchar](50) NOT NULL,
[VOUCHERNO] [int] NOT NULL,
[DATE] [datetime] NOT NULL,
[AMOUNT] [decimal](18, 2) NOT NULL,
[DRPARTY] [int] NOT NULL,
[CRPARTY] [int] NOT NULL,
[DETAILS] [nvarchar](50) NOT NULL,
[ORIGIN] [nvarchar](50) NULL,
[ORIGINID] [int] NOT NULL,
[ORIGINDETAILS] [nvarchar](max) NULL,
[CREATE_TIMESTAMP] [datetime] NOT NULL DEFAULT ('1900-01-01T00:00:00.000'),
[LAST_EDIT_TIMESTAMP] [datetime] NOT NULL DEFAULT ('1900-01-01T00:00:00.000'),
[TRANSACTION_TYPE] [nvarchar](50) NULL,
CONSTRAINT [PK_dbo.Voucher]
PRIMARY KEY CLUSTERED ([ID] ASC)
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
This is the error I am getting when creating FK relationship via Microsoft SQL Server Management Studio. Both tables are empty.
'Account' table saved successfully
'Voucher' table - Unable to create relationship 'FK_Voucher_Account1'. The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Voucher_Account1". The conflict occurred in database "SKUMAR", table "dbo.Account", column 'ID'
I want to create a relation between Account.ID -> Voucher.DRPARTY and Account.ID -> Voucher.CRPARTY but I am unable to create second FK relationship.
May I know how to solve this?
There is a possibility of conflicted foreign key error because of data mismatch between Voucher(CRPARTY) column and Account(Id) column. Rows available in CRPARTY table must be in Account table.
Verify using below query.
SELECT * FROM Voucher WHERE CRPARTY NOT IN (SELECT Id FROM Account);
I was able to create 2 FKs to 1 PK. http://rextester.com/WMAT80057
You can delete the FK relationships between your tables and use this script to create them. Hopefully, your tables do not have non matching data.
ALTER TABLE [dbo]. [Voucher] WITH CHECK ADD CONSTRAINT [FK_ACCOUNT_ID_VOUCHER_DRPARTY] FOREIGN KEY ([DRPARTY]) REFERENCES [dbo]. [Account]([ID])
GO
ALTER TABLE [dbo]. [Voucher] CHECK CONSTRAINT [FK_ACCOUNT_ID_VOUCHER_DRPARTY]
GO
ALTER TABLE [dbo]. [Voucher] WITH CHECK ADD CONSTRAINT [FK_ACCOUNT_ID_VOUCHER_CRPARTY] FOREIGN KEY ([CRPARTY]) REFERENCES [dbo]. [Account]([ID])
GO
ALTER TABLE [dbo]. [Voucher] CHECK CONSTRAINT [FK_ACCOUNT_ID_VOUCHER_CRPARTY]
GO

Implementing custom fields in a database for large numbers of records

I'm developing an app which requires a user defined custom fields on a contacts table. This contact table can contain many millions of contacts.
We're looking at using a secondary metadata table which stores information about the fields, along with a tertiary value table which stores the actual data.
Here's the rough schema:
CREATE TABLE [dbo].[Contact](
[ID] [int] IDENTITY(1,1) NOT NULL,
[FirstName] [nvarchar](max) NULL,
[MiddleName] [nvarchar](max) NULL,
[LastName] [nvarchar](max) NULL,
[Email] [nvarchar](max) NULL
)
CREATE TABLE [dbo].[CustomField](
[ID] [int] IDENTITY(1,1) NOT NULL,
[FieldName] [nvarchar](50) NULL,
[Type] [varchar](50) NULL
)
CREATE TABLE [dbo].[ContactAndCustomField](
[ID] [int] IDENTITY(1,1) NOT NULL,
[ContactID] [int] NULL,
[FieldID] [int] NULL,
[FieldValue] [nvarchar](max) NULL
)
However, this approach introduces a lot of complexity, particularly with regard to importing CSV files with multiple custom fields. At the moment this requires a update/join statement and a separate insert statement for every individual custom field. Joins would also be required to return custom field data for multiple rows at once
I've argued for this structure instead:
CREATE TABLE [dbo].[Contact](
[ID] [int] IDENTITY(1,1) NOT NULL,
[FirstName] [nvarchar](max) NULL,
[MiddleName] [nvarchar](max) NULL,
[LastName] [nvarchar](max) NULL,
[Email] [nvarchar](max) NULL
[CustomField1] [nvarchar](max) NULL
[CustomField2] [nvarchar](max) NULL
[CustomField3] [nvarchar](max) NULL /* etc, adding lots of empty fields */
)
CREATE TABLE [dbo].[ContactCustomField](
[ID] [int] IDENTITY(1,1) NOT NULL,
[FieldIndex] [int] NULL,
[FieldName] [nvarchar](50) NULL,
[Type] [varchar](50) NULL
)
The downside of this second approach is that there is a finite number of custom fields that must be specified when the contacts table is created. I don't think that's a major hurdle given the performance benefits it will surely have when importing large CSV files, and returning result sets.
What approach is the most efficient for large numbers of rows? Are there any downsides to the second technique that I'm not seeing?
Microsoft introduced sparse columns exactly for this type of problems. Tha point is that in a "classic" design you end up with large number of columns, most of the NULLs for any particular row. Same here with sparse columns, but NULLs don't require any storage. Moreover, you can create sets of columns and modify sets with XML.
Performance- and storage-wise, sparse columns are the winner.
http://technet.microsoft.com/en-us/library/cc280604.aspx
uery performance. Query performance for any "property bag table" approach is funny and comically slow - but if you need flexibility you can either have a dynamic table that is changed via an editor OR you have a property bag table. So when you need it, you need it.
But expect the performance to be slow.
The best approach would likely be a ContactCustomFields table which has - fields that are determined by an editor.

How do I insert into two tables all at once in a stored procedure? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I INSERT data into two tables simultaneously in SQL Server?
Doing a project for school so any help would be great thank you!
I have two tables - how do I insert into two tables? So both tables are linked.
First table is called Customer with primary key called CID that auto increments
CREATE TABLE [dbo].[Customer](
[CID] [int] IDENTITY(1,1) NOT NULL,
[LastName] [varchar](255) NOT NULL,
[FirstName] [varchar](255) NOT NULL,
[MiddleName] [varchar](255) NULL,
[EmailAddress] [varchar](255) NOT NULL,
[PhoneNumber] [varchar](12) NOT NULL
CONSTRAINT [PK__CInforma__C1F8DC5968DD69DC] PRIMARY KEY CLUSTERED
(
And a second table called Employment that has a foreign key linked to the parent table
CREATE TABLE [dbo].[Employment](
[EID] [int] IDENTITY(1,1) NOT NULL,
[CID] [int] NOT NULL,
[Employer] [varchar](255) NOT NULL,
[Occupation] [varchar](255) NOT NULL,
[Income] [varchar](25) NOT NULL,
[WPhone] [varchar](12) NOT NULL,
CONSTRAINT [PK__Employme__C190170BC7827524] PRIMARY KEY CLUSTERED
(
You need to do something like this:
DECLARE #NewID INT
INSERT INTO Customer(LastName,FirstName,......) VALUES(Value1, Value2, .....)
SELECT #NewID = SCOPE_IDENTITY()
INSERT INTO Employment(CID,Employer,.....) VALUES(#NewID, ValueA,..........)
SCOPE_IDENTITY: Returns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch.

Get value from other foreign key table based on current table value

I am working on a project where I need to extract the data from excel sheet to SQL Server
, well that bit have done successfully. Now my problem is that for a particular column
called product size, I want to update current table based on product size in other table, I am really very confused , please help me out
Please find the table structure
CREATE TABLE [dbo].[T_Product](
[ProductID] [int] IDENTITY(1,1) NOT NULL,
[PartNo] [nvarchar](255) NULL,
[CategoryID] [int] NULL,
[MaterialID] [float] NULL,
[WireformID] [float] NULL,
[ProductName] [nvarchar](50) NULL,
[ProductSize] [nvarchar](50) NULL,
[ProductLength] [varchar](20) NULL,
[ProductActive] [bit] NULL,
[ProductImage] [varchar](60) NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[T_ProductSize](
[Code] [int] IDENTITY(1,1) NOT NULL,
[ProductSize] [nvarchar](50) NULL,
[Length] [nchar](20) NULL
) ON [PRIMARY]
GO
OK, so ignore the previous answer, I got the wrong end of the stick!!
You want something like this I think:
UPDATE T_Product
SET [ProductLength] = ps.[Length]
FROM T_Product p
INNER JOIN T_ProductSize ps
ON p.[ProductSize] = ps.[ProductSize]
That will take the Length value from T_ProductSize and place it in T_Product.ProductLength based on the value of T_Product.ProductSize
You mention a foreign key but you haven't included a definition for it. Is it between the two tables in your example? If so, which columns make the key? Is product size the key? If so, then your question doesn't make a lot of sense as the value will be the same in both tables.
Is it possible that you mean the product size is to be stored in a separate table and not in the T_Product table? In that case then instead of ProductSize in T_Product you will want the code from the T_ProductSize table (can I also suggest that instead of 'code' you call it 'ProductSizeCode' or better yet 'ProductSizeId' or similar? having columns simply called code can be very confusing as you have no simple way of know what table that value is in). Also, you should always create a primary key on each table: You cannot have a foreign key without one. They don't have to be clustered, that will depend upon hwo your search the table, but I am using a clustered PK for this example. That would give you something like this:
CREATE TABLE [dbo].[T_Product](
[ProductID] [int] IDENTITY(1,1) NOT NULL,
[PartNo] [nvarchar](255) NULL,
[CategoryID] [int] NULL,
[MaterialID] [float] NULL,
[WireformID] [float] NULL,
[ProductName] [nvarchar](50) NULL,
[ProductSizeId] [int] NOT NULL,
[ProductLength] [varchar](20) NULL,
[ProductActive] [bit] NULL,
[ProductImage] [varchar](60) NULL
CONSTRAINT [PK_T_Product] PRIMARY KEY CLUSTERED
(
[ProductID] ASC
) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[T_ProductSize](
[ProductSizeId] [int] IDENTITY(1,1) NOT NULL,
[ProductSize] [nvarchar](50) NULL,
[Length] [nchar](20) NULL
CONSTRAINT [PK_T_ProductSize] PRIMARY KEY CLUSTERED
(
[ProductSizeId] ASC
) ON [PRIMARY]
) ON [PRIMARY]
GO
--Now add your foreign key to T_Product.
ALTER TABLE [T_Product] WITH NOCHECK ADD CONSTRAINT [FK_Product_ProductSize] FOREIGN KEY([ProductSizeId])
REFERENCES [T_ProductSize] ([ProductSizeId])
GO
ALTER TABLE [T_Product] CHECK CONSTRAINT [FK_Product_ProductSize]
GO
Now, to retrieve your product along with the product size use something like this:
SELECT p.[ProductID], p.[PartNo], p.[CategoryID], p.[MaterialID], p.[WireformID], p.[ProductName],
ps.[ProductSize], ps.[Length], p.[ProductLength], p.[ProductActive], p.[ProductImage]
FROM [T_Product] p
INNER JOIN [T_ProductSize] ps
ON ps.[ProductSizeId] = p.[ProductSizeId]
If I have understood you correctly, then this is what I think you're after. If not, then have another go at explaining what it is you need and I'll try again.
Try this...
UPDATE t2
SET t2.ProductLength = t1.Length
FROM dbo.T_ProductSize t1
INNER JOIN dbo.T_Product t2 ON t1.ProductSize = t2.ProductSize

adding multiple values to sql

say i have a column defined as Address. also, I have a record, let's call it Rudy's. now Rudy's has multiple addresses, so I need to include multiple address so that they are all searchable. what is the best way to approach a solution in SQL?
You should add a child table with an Address column. You will have one to many relation where address is stored in a child table. You can add as many addresses per user as you want. Also you can add extra info like address type (home, work or primary, secondary ect.)
I wouldn't go for one column for address. If this is a postal address it is better to have more columns such as street, town, house number ect. Then you can have an advantage of using indexes on your columns.
You could try something like this:
CREATE TABLE [dbo].[Person](
[PersonId] [int] IDENTITY(1,1) NOT NULL,
[FullName] [varchar](50) NULL,
CONSTRAINT [PK_Person] PRIMARY KEY CLUSTERED ([PersonId] ASC))
GO
CREATE TABLE [dbo].[Addresses](
[AddressId] [int] IDENTITY(1,1) NOT NULL,
[PersonId] [int] NOT NULL,
[AddressLine1] [varchar](50) NULL,
[AddressLine2] [varchar](50) NULL,
[City] [varchar](50) NULL,
[State] [varchar](4) NULL,
[Country] [varchar](50) NULL,
CONSTRAINT [PK_Addresses] PRIMARY KEY CLUSTERED ([AddressId] ASC))
GO
ALTER TABLE [dbo].[Addresses]
WITH CHECK ADD CONSTRAINT [FK_Addresses_Person] FOREIGN KEY([PersonId])
REFERENCES [dbo].[Person] ([PersonId])
GO
ALTER TABLE [dbo].[Addresses] CHECK CONSTRAINT [FK_Addresses_Person]
GO
Of course you can have it as complex as you want and follow the previous advice for storing address types etc.
It might help to download MS examples from http://sqlserversamples.codeplex.com/ and follow their best practices.