473,609 Members | 1,861 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to populate an empty table using INSERT commands

34 New Member
Hi, I'm a newbie at this but how can I populate a table with data from other tables by using INSERT statements? Below is of what I have so far, I have to populate the PERSON_PROFILE table. I've tried using INSERT with SELECT and UPDATE commands which just dont work. I cant input data in one column at a time either since when I created the table, I specified all fields to be NOT NULL.

CREATE TABLE PERSON ( */this table was originally created in assignment 1*/
Person_Id int NOT NULL,
First_Name varchar(20) NOT NULL,
Last_Name varchar(20) NOT NULL,
Middle_Name_Ini tial char(1) NULL,
Date_Of_Birth DateTime NOT NULL,
Employment_Stat us char(1) NOT NULL,
CONSTRAINT ck_employmentSt ats
CHECK(Employmen t_Status IN ('F', 'P')),
CONSTRAINT pk_person
PRIMARY KEY (Person_Id),
);
/*current assignment*/
CREATE TABLE BADGE (
Badge_Number_Id int NOT NULL,
Issuer_Person int NOT NULL,
Assigned_Person int NOT NULL,
Date_Issued DateTime NOT NULL,
CONSTRAINT pk_badge_number _id
PRIMARY KEY(Badge_Numbe r_Id),
);

BULK INSERT DB2914.dbo.[BADGE]
FROM 'C:\Documents and Settings\Jthep\ My Documents\SQL Server Management Studio\Projects \S2914-HW1\BadgeData.t xt'
WITH (FIELDTERMINATO R = ',', ROWTERMINATOR = '\n')

ALTER TABLE PERSON
ADD Badge_Number int;

UPDATE PERSON
SET Badge_Number = (SELECT Badge_Number_Id
FROM BADGE
WHERE Assigned_Person = Person_Id);

ALTER TABLE BADGE
DROP COLUMN Assigned_Person ;


ALTER TABLE PERSON
ADD CONSTRAINT fk_badge_number _id
FOREIGN KEY (Badge_Number) REFERENCES BADGE(Badge_Num ber_Id);

CREATE TABLE PROFILE (
Profile_Code varchar(4) NOT NULL,
Profile_Descrip tion varchar(100) NOT NULL,
CONSTRAINT ck_profile_code
CHECK(Profile_C ode IN ('Scty', 'Eval')),
CONSTRAINT pk_profile_code
PRIMARY KEY (Profile_Code),
);

CREATE TABLE PERSON_PROFILE (
Person_Profile_ Code varchar (4) NOT NULL,
Person_Profile_ Id int NOT NULL,
Profile_Assign_ Date DateTime NOT NULL,
CONSTRAINT pk_person_profi le
PRIMARY KEY(Person_Prof ile_Code, Person_Profile_ Id),
CONSTRAINT fk_person_profi le_code
FOREIGN KEY (Person_Profile _Code) REFERENCES PROFILE (Profile_Code),
CONSTRAINT fk_person_profi le_id
FOREIGN KEY (Person_Profile _Id) REFERENCES PERSON (Person_Id),
);

INSERT INTO PROFILE
VALUES('Scty', 'A person authorized to issue organization badges');
INSERT INTO PROFILE
VALUES('Eval', 'A person authorized to perform evaluations');
Oct 6 '07 #1
7 9772
azimmer
200 Recognized Expert New Member
Hi, I'm a newbie at this but how can I populate a table with data from other tables by using INSERT statements? Below is of what I have so far, I have to populate the PERSON_PROFILE table. I've tried using INSERT with SELECT and UPDATE commands which just dont work. I cant input data in one column at a time either since when I created the table, I specified all fields to be NOT NULL.

CREATE TABLE PERSON ( */this table was originally created in assignment 1*/
Person_Id int NOT NULL,
First_Name varchar(20) NOT NULL,
Last_Name varchar(20) NOT NULL,
Middle_Name_Ini tial char(1) NULL,
Date_Of_Birth DateTime NOT NULL,
Employment_Stat us char(1) NOT NULL,
CONSTRAINT ck_employmentSt ats
CHECK(Employmen t_Status IN ('F', 'P')),
CONSTRAINT pk_person
PRIMARY KEY (Person_Id),
);
/*current assignment*/
CREATE TABLE BADGE (
Badge_Number_Id int NOT NULL,
Issuer_Person int NOT NULL,
Assigned_Person int NOT NULL,
Date_Issued DateTime NOT NULL,
CONSTRAINT pk_badge_number _id
PRIMARY KEY(Badge_Numbe r_Id),
);

BULK INSERT DB2914.dbo.[BADGE]
FROM 'C:\Documents and Settings\Jthep\ My Documents\SQL Server Management Studio\Projects \S2914-HW1\BadgeData.t xt'
WITH (FIELDTERMINATO R = ',', ROWTERMINATOR = '\n')

ALTER TABLE PERSON
ADD Badge_Number int;

UPDATE PERSON
SET Badge_Number = (SELECT Badge_Number_Id
FROM BADGE
WHERE Assigned_Person = Person_Id);

ALTER TABLE BADGE
DROP COLUMN Assigned_Person ;


ALTER TABLE PERSON
ADD CONSTRAINT fk_badge_number _id
FOREIGN KEY (Badge_Number) REFERENCES BADGE(Badge_Num ber_Id);

CREATE TABLE PROFILE (
Profile_Code varchar(4) NOT NULL,
Profile_Descrip tion varchar(100) NOT NULL,
CONSTRAINT ck_profile_code
CHECK(Profile_C ode IN ('Scty', 'Eval')),
CONSTRAINT pk_profile_code
PRIMARY KEY (Profile_Code),
);

CREATE TABLE PERSON_PROFILE (
Person_Profile_ Code varchar (4) NOT NULL,
Person_Profile_ Id int NOT NULL,
Profile_Assign_ Date DateTime NOT NULL,
CONSTRAINT pk_person_profi le
PRIMARY KEY(Person_Prof ile_Code, Person_Profile_ Id),
CONSTRAINT fk_person_profi le_code
FOREIGN KEY (Person_Profile _Code) REFERENCES PROFILE (Profile_Code),
CONSTRAINT fk_person_profi le_id
FOREIGN KEY (Person_Profile _Id) REFERENCES PERSON (Person_Id),
);

INSERT INTO PROFILE
VALUES('Scty', 'A person authorized to issue organization badges');
INSERT INTO PROFILE
VALUES('Eval', 'A person authorized to perform evaluations');
According to the rules of the Forum I shall not give you a complete solution, as this looks very much like an assignment. However, I give you hints:

1. The general format of INSERTing values from one table into another is:
Expand|Select|Wrap|Line Numbers
  1. INSERT INTO dest_table
  2. SELECT myColumn1, myColumn2, ...
  3. FROM source_table
  4.  
2. Any column in a SELECT statement (even inside an INSERT!) can be a constant or any other expression.

3. There is a "SELECT ... INTO ..." statement as well; you may or may not want to use it, though.

And a last one: read the help (that of INSERT and SELECT INTO, of course).
Oct 6 '07 #2
jthep
34 New Member
Thanks for the reply. I dont really need the full solution, an approach to handling/hints are great. With just solutions, I know I wont get how it works. And I really need to understand how it works. I tried doing the INSERT with SELECT, the only thing is the three different fields (the profile badge code, the id, and date issued) I must put in are in three seperate tables that have about almost all different fields. When I do the INSERT, I have to put in all three fields because if I only try to put in one field or two fields, the SQL will give me an error that states, unable to insert null into table. Thats because I have three fields that does not allow NULLS.

The three tables are:

profile table that contains two fields, badge code which have values Stcy and Eval and a description field of 'people authorized to issue badges' and 'people authorized to perform evaluations' respectively. I will need to use these values for the first column of the new table

Badge table that contains three fields, the badge id (or badge number which has an int value) that was issued, the issuer person which is the person Id from the third table below (Person) and the issued date. the issuer person would have a badge code of 'Stcy' in the new table since they are authorized to issuer badges.

The last table is the Person table which contains fields, person id, last name, first name, birth date, badge id (badge number) etc as listed in the previous post. Any person Id that is not in the Badge Table under the field issuer person will be classified as 'Eval' in the first field of the new table.

Then for the last column, I can set the issued date to any date I want. I was also thinking that since I was provided with the Badge Data to do the bulk insert for the Badge table, if will I be able to use that data to do a bulk insert for the new table called Person_Profile then update the values in the graph. The only thing is that the data contains data for four fields vs the three fields define in the Person_Profile. Is it possible to specify which fields I want to insert to the table from the data? I know at the begining when I made the Badge table, it had four fields, but as there were specific instructions that I had to follow before I got stuck, the current results I had for the Badge table is now three fields.

*EDIT: Sorry I didnt fully read your hints. Question, what you said that the fields in the SELECT statment can be constant. By that do you mean we can hardcode the value into the the statement as in SELECT 'Stcy', person_id, '10/21/2001'? I dont know how that will work since the profile table will return only one row, badge will return many rows since I'm inserting all the id numbers listed in badge. If I added another column in badge name called badge code and set the code to 'Stcy' or I if do that in the person profile and set those person id whos not in badge to 'Eval' and those are to 'Stcy'. Then I can probably do a select statement and delete the fields from other tables after. However, the instructions were to just populate the table using INSERT statements.

Sorry long post.
Oct 6 '07 #3
azimmer
200 Recognized Expert New Member
Thanks for the reply. I dont really need the full solution, an approach to handling/hints are great. With just solutions, I know I wont get how it works. And I really need to understand how it works. I tried doing the INSERT with SELECT, the only thing is the three different fields (the profile badge code, the id, and date issued) I must put in are in three seperate tables that have about almost all different fields. When I do the INSERT, I have to put in all three fields because if I only try to put in one field or two fields, the SQL will give me an error that states, unable to insert null into table. Thats because I have three fields that does not allow NULLS.

The three tables are:

profile table that contains two fields, badge code which have values Stcy and Eval and a description field of 'people authorized to issue badges' and 'people authorized to perform evaluations' respectively. I will need to use these values for the first column of the new table

Badge table that contains three fields, the badge id (or badge number which has an int value) that was issued, the issuer person which is the person Id from the third table below (Person) and the issued date. the issuer person would have a badge code of 'Stcy' in the new table since they are authorized to issuer badges.

The last table is the Person table which contains fields, person id, last name, first name, birth date, badge id (badge number) etc as listed in the previous post. Any person Id that is not in the Badge Table under the field issuer person will be classified as 'Eval' in the first field of the new table.

Then for the last column, I can set the issued date to any date I want. I was also thinking that since I was provided with the Badge Data to do the bulk insert for the Badge table, if will I be able to use that data to do a bulk insert for the new table called Person_Profile then update the values in the graph. The only thing is that the data contains data for four fields vs the three fields define in the Person_Profile. Is it possible to specify which fields I want to insert to the table from the data? I know at the begining when I made the Badge table, it had four fields, but as there were specific instructions that I had to follow before I got stuck, the current results I had for the Badge table is now three fields.

*EDIT: Sorry I didnt fully read your hints. Question, what you said that the fields in the SELECT statment can be constant. By that do you mean we can hardcode the value into the the statement as in SELECT 'Stcy', person_id, '10/21/2001'? I dont know how that will work since the profile table will return only one row, badge will return many rows since I'm inserting all the id numbers listed in badge. If I added another column in badge name called badge code and set the code to 'Stcy' or I if do that in the person profile and set those person id whos not in badge to 'Eval' and those are to 'Stcy'. Then I can probably do a select statement and delete the fields from other tables after. However, the instructions were to just populate the table using INSERT statements.

Sorry long post.
Hi, I'll try to be short (for now, that is :)). Let me try to rephrase what you seem to want; tell me if it's right or wrong.

You want to fill the PERSON_PROFILE table with INSERTs in such a way that:
  • all persons from the PERSON table get inserted (as Person_Profile_ ID)
  • Profile_Code is 'Stcy' or 'Eval' based on the person's existence/non-existence in the BADGE table (as Assigned_person )
  • Profile_Assign_ Date is Date_Issued from the BADGE table (it there's a corresponding entry) and today otherwise
Oct 7 '07 #4
jthep
34 New Member
Yep, that's basically it.

Person has a relationship with Badge through the badge number.
Person_Profile has a relationship with Profile through the profile code
Person_Profile also has a relationship with Person through Id.

Thanks for trying to help me, it gets confusing switching between C and SQL as I'm taking both concurrently. Too much codes overload.
Oct 8 '07 #5
azimmer
200 Recognized Expert New Member
Yep, that's basically it.

Person has a relationship with Badge through the badge number.
Person_Profile has a relationship with Profile through the profile code
Person_Profile also has a relationship with Person through Id.

Thanks for trying to help me, it gets confusing switching between C and SQL as I'm taking both concurrently. Too much codes overload.
OK -- but this one is going to be longer.

NB: Person profile is basicly a switching table; these are not normally populated from existing data (because they cannot be). In your case it is possible, though.

Some of the data you need to insert is in the PERSON table, some in the BADGE table, and -- in a somewhat tricky way -- some will be constants (namely the profiles codes).

In the first step, let's join the two relevant tables in a "left outer" manner, so that each line in PERSON get selected along with data in the BADGE table if they exist:
Expand|Select|Wrap|Line Numbers
  1. SELECT
  2.     p.Person_Id,
  3.     b.Badge_Number_Id
  4. FROM
  5.     PERSON p LEFT OUTER JOIN BADGE b ON p.Badge_Number = b.Badge_Number
  6.  
(Do run it and see what the result looks like.)

Now, let's throw in the first trick: "Profile code". If b.Badge_Number_ Id is NULL it has to be "Eval", "Stcy" otherwise. (When the left outer join cannot find a matching row in BADGE it fills the corresponding fields with NULLs.)
Expand|Select|Wrap|Line Numbers
  1. SELECT
  2.     p.Person_Id as Person_Profile_ID,
  3.     case when b.Badge_Number_Id is null then 'Eval' else 'Stcy' end as Profile_Code
  4. FROM
  5.     PERSON p LEFT OUTER JOIN BADGE b ON p.Badge_Number = b.Badge_Number
  6.  
And the last adjustment: "Profile_Assign _Date"; it goes along a similar line (but I coded it differently so that you can see an alternative):
Expand|Select|Wrap|Line Numbers
  1. SELECT
  2.     p.Person_Id as Person_Profile_ID,
  3.     case when b.Badge_Number_Id is null then 'Eval' else 'Stcy' end as Profile_Code,
  4.     COALESCE(b.Date_Issued,getdate()) as Profile_Assign_Date
  5. FROM
  6.     PERSON p LEFT OUTER JOIN BADGE b ON p.Badge_Number = b.Badge_Number
  7.  
Hope it helps. From this on, though, I'll have to leave you on your own with the INSERT (but as a hint: it is obviously an INSERT INTO ... SELECT construction).

Ask if you have questions regarding the SELECTs; and please, if I may ask you, read the help for all unknown constructs (e.g. OUTER JOIN, CASE ... WHEN, and COALESCE if you don't know them).
Oct 8 '07 #6
jthep
34 New Member
Thanks soo much. I have no problem with the INSERT portion as long as I know how to get the data from the tables. Where can I go to read the articles? I went up to the SQL Server section under Articles, but I only came up with one page with a couple threads.
Oct 8 '07 #7
azimmer
200 Recognized Expert New Member
Thanks soo much. I have no problem with the INSERT portion as long as I know how to get the data from the tables. Where can I go to read the articles? I went up to the SQL Server section under Articles, but I only came up with one page with a couple threads.
This is a good place to start with helps: http://technet.microso ft.com/en-us/library/aa299742(SQL.80 ).aspx
Oct 9 '07 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

2
16065
by: ImraneA | last post by:
Hi there Application : Access v2K/SQL 2K Jest : Using sproc to append records into SQL table Jest sproc : 1.Can have more than 1 record - so using ';' to separate each line from each other.
17
12810
by: Dr NoName | last post by:
Help! I have a table that multiple processes must be able to write to concurrently. However, it for some reason gets locked in exclusive mode. I narrowed it down to one SQL statement + some weirdness with foreign keys. To debug this, I opened two psql sessions and typed in the sql statements manually. Here is the situation: CREATE TABLE take2
2
3231
by: 2003et | last post by:
How to save data from a created dataset to an empty sqlserver table? tables have identically the same schema. Thanks,
10
7387
by: John Smith | last post by:
I know that uploading an image to a database has been covered, oh, about 3 trillion times. However, I haven't found anything covering uploading to a MySQL database with .net. Please don't recommend storing the image to the filesystem and only keeping a pointer to that in the table. I want to dump the image to a table. My code dumps the data into the table, however, I get the following error when trying to view the image "the image ......
10
1442
by: sparks | last post by:
So far I have tried the microsoft version of this, and lost the table LOl so I tried this way to write to two tables carrying over the autoid but so far I can not get the autonumber and put it in the other table. thanks big time for any help maybe I tried to do it the dumb way but it looks to me like this should work probably not :)
5
2950
by: Wayne Wengert | last post by:
I am using VB ASP.NET. In my page I convert an uploaded XML file to a dataset as follows: Dim ds1 As DataSet = New DataSet ds1.ReadXml(strPathName, XmlReadMode.Auto) Now I want to append all the rows of ds1 to an existing table in an SQL Server database. I know I can do things like looping through the dataset and issuing Update SQL statements to do this but I suspect there is a better
6
3613
by: Jchick | last post by:
Im a newbie with a sql table in a MSDE database that contains fields of CustName, BrokerName, Type, Status. I am trying to write a trigger that does this: 1. When a new record in a table is added, I would like the selected fields to be copied to another table (call it Master). 2. If that Master table already contains a record where the CustName = CustName, then simply ignore. If CustName does not match anything, then add the record to...
2
2725
by: mike | last post by:
I'm looking for an efficient way to populate derived columns when I insert data into a table in SQL Server. In Informix and PostgreSQL this is easily done using the "for each row..." syntax, but all I've been able to come up with for SQL Server is the following: create table testtrigger(id integer unique, b integer, c integer) go create trigger testtrigger_ins on testtrigger for insert as
4
6565
by: Nate | last post by:
I am looking to populate a Schedule table with information from two other tables. I am able to populate it row by row, but I have created tables that should provide all necessary information for me to be able to automatically populate a "generic" schedule for a few weeks or more at a time. The schedule table contains: (pk) schedule_id, start_datetime, end_datetime, shift_employee,
0
8573
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8541
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8222
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8406
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6057
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4021
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4085
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2531
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1389
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.