Store array in SQL Server 2008
I am developing a contact manager application using SQL Server 2008 (service-based database) . Most contacts have several emails or several phone number开发者_StackOverflow社区s. So is there a way to store an array as a datatype in SQL Server? Or does anyone have an alternative to this way?
You'll want to create separate tables, with a row per contact number or email address.
CREATE TABLE Contacts (contactId int, name varchar(128), etc, etc
CREATE TABLE ContactEmail (contactId int, emailAddress varchar(128), etc
CREATE TABLE ContactPhone (contactId int, phoneNumber varchar(128), etc
This will allow you to modify individual numbers/emails, remove them, add them, etc, without requiring an external program to unpack an array.
But if you really want to store it denormalized, you could transform the array into a delimited string. . put a delimiter between each email address (with the appropriate magic to make sure an address doesn't already contain the delimiter) then split it on the way back out.
No there isn't an array type in SQL.
You should create a phonenumbers table and store one phone number per row use and use a foreign key (called, for example, person_id) to refer to the person table.
One other option you can use is to store the contact information as an XML document in a XML type field in your table. I would only do this if I am not trying to search for people based on some part of that contact information.
For example if you are think you might be interested in finding all your contacts who have phone numbers with a specific area code then you will want to make that a separate table and relate it instead of storing it this way.
I know that you can actually query the XML in SQL Server 2008, but it really depends on how many records you are going to have in your contact list as parsing all that XML on a lot of data will be very slow compared to having separate tables.
You can use a Table Variable, to use this you should use a DDL Create Table, but you need to write first the at (@). With this you have an Array.... but you CANNOT store this on a table because a table is an array it selft. I you really need to have a data structure inside of your table, you should use an XML. As I understand since SQL Server 2000 has several features to work with XML.
Perhaps if you can tell me more details of your reasons to do this... I can give you back more ideas!
I hope my answear can help you
精彩评论