Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store multiple values in single field in SQL database?

Tags:

My problem is, I want to store a person with multiple phone numbers in the database. for a single variable for number will store only one number for each.

Now if I want to add another phone number it is creating another new record with the same details but the different number.

I want to display all these numbers together. Can anyone help?

like image 618
Krutika Sonawala Avatar asked Jul 21 '14 12:07

Krutika Sonawala


People also ask

How do I combine multiple values in one cell in SQL?

You can concatenate rows into single string using COALESCE method. This COALESCE method can be used in SQL Server version 2008 and higher. All you have to do is, declare a varchar variable and inside the coalesce, concat the variable with comma and the column, then assign the COALESCE to the variable.

How do I store a list of values in one column in SQL Server?

In the design all users data will be stored in a series of columns in a single table but one of the columns requires to store a list of values, for example: 'column1' will store the username , 'column2' will store the userID and 'column3' will store a list of items that will change over time.


2 Answers

You could use a second table to store the numbers, and link back with a Foreign Key:

PersonTable: PersonId, Name, etc..

The second table will hold the numbers...

NumbersTable: NumberId, PersonId(fk), Number

You could then get the numbers like this...

SELECT p.Name, n.Number from PersonTable p Left Join NumbersTable n
on p.PersonId = n.PersonId

This is a simple example. I have used a LEFT JOIN here in case a person doesn't supply their number. Also, this is just pseudo code, so don't use Table in the name.

like image 73
Christian Phillips Avatar answered Oct 04 '22 21:10

Christian Phillips


You should create separate tables for Person and PhoneNumber.

CREATE TABLE Person(PersonId int IDENTITY(1,1) PRIMARY KEY)

CREATE TABLE Phone(
    PersonId int,
    PhoneNumber varchar(20),
    CONSTRAINT PK_Phone PRIMARY KEY(PersonId,PhoneNumber),
    CONSTRAINT FK_PersonId FOREIGN KEY(PersonId) REFERENCES Person(PersonId)
    )
like image 32
semao Avatar answered Oct 04 '22 21:10

semao