how to fill a table with using some of the data of other tables - sql-server

I need to create a new table called “customer” that include some of columns from the “user table”, and also “project table”. I built my suppliers table with specific column names and I need to fill its column by using data of the other tables. Finally I am trying to finish; when user create a new account and project, the customer table automatically fill with some of other two tables varieties with different column names.
INFO: I have three different user types such as “suppliers”, “costumers”, “managers”. I am holding their information(include user types) in one table called users.

Use the following query as an example and write a query to insert the rows to destination table from source table.
Ex:-
INSERT INTO TestTable (FirstName, LastName)
SELECT FirstName, LastName
FROM Person.Contact
WHERE EmailPromotion = 2
Note: Use Join in the select query to join two tables

The 1st step would be to couple the data from the different tables using a table join command. If you can create a search result that matched your new table, then creating the table is simple a call to the below.
Create table CUSTOMER as (Select ...)
"when user create a new account and project.." this is something you plan on doing at run time in your application and not something you need to collate using sql at this point?

Related

SQL server : Inserting/updating missing data from one table to another

I have two table "Container" and "Control". These are existing tables and there is no foreign key relationship between the two. These are also very old tables so are not normalized. And I cannot change the structure now.
Below is the structure of the two tables.
Container table :
Control Table :
The Name field in Control table contains CTableName+CPName from Container table.
I want to update the columnName field of Control table with the value of CID column of Container table. and also want to insert one more record (for ctable2 i.e the fourth row in final Control table below) in Control table.
The tablename and columnname columns have will always be have default values.
The final Control table should look like this:
How do I do this?
I hope you want to apply this fix because you want normalize your table structure.
Try this:
First step:
In this way you'll UPDATE all Control rows with the value of Container table where the couple fields CTableName and CPName are the same of Name (excluding the rows of Container with the same couple fields)
UPDATE Control
SET ColumnValue = (
SELECT c.CID
FROM Container c
WHERE c.CTableName + '+' + c.CPName = Control.Name
AND NOT EXISTS(
SELECT 'PREVIOUS'
FROM Container c2
WHERE c.CTableName = c2.CTableName
AND c.CPName = c2.CPName
AND c.CID < c2.CID
)
),
TableName = 'default', ColumnName = 'default'
WHERE ColumnValue IS NULL
Second step:
Adding elements don't present in Control table
INSERT INTO Control (field list)
SELECT field list
FROM Container co
WHERE NOT EXISTS(
SELECT 'in_control'
FROM Control ct
WHERE co.CID = ct.ColumnValue
)
After these two steps you can drop column Name in Control table
I am an Oracle plsql programmer and worked with Sql-server as well.
First you should describe the relationship between the 2 tables, in the end i could figger it out but it's better you explain it yourself.
To update a table with information from another table you should ask yourself:
- when should the update take place?
- what are the conditions to start the update?
- how should the update be done?
In Oracle there is a database object called a trigger. It's quite a handy object and probably just what you need. I believe that sql-server has it too.
Pls fee free to ask any questions but do read the sql-server appropriate manual as well.
Good luck, Edward.

Merge query using two tables in SQL server 2012

I am very new to SQL and SQL server, would appreciate any help with the following problem.
I am trying to update a share price table with new prices.
The table has three columns: share code, date, price.
The share code + date = PK
As you can imagine, if you have thousands of share codes and 10 years' data for each, the table can get very big. So I have created a separate table called a share ID table, and use a share ID instead in the first table (I was reliably informed this would speed up the query, as searching by integer is faster than string).
So, to summarise, I have two tables as follows:
Table 1 = Share_code_ID (int), Date, Price
Table 2 = Share_code_ID (int), Share_name (string)
So let's say I want to update the table/s with today's price for share ZZZ. I need to:
Look for the Share_code_ID corresponding to 'ZZZ' in table 2
If it is found, update table 1 with the new price for that date, using the Share_code_ID I just found
If the Share_code_ID is not found, update both tables
Let's ignore for now how the Share_code_ID is generated for a new code, I'll worry about that later.
I'm trying to use a merge query loosely based on the following structure, but have no idea what I am doing:
MERGE INTO [Table 1]
USING (VALUES (1,23-May-2013,1000)) AS SOURCE (Share_code_ID,Date,Price)
{ SEEMS LIKE THERE SHOULD BE AN INNER JOIN HERE OR SOMETHING }
ON Table 2 = 'ZZZ'
WHEN MATCHED THEN UPDATE SET Table 1.Price = 1000
WHEN NOT MATCHED THEN INSERT { TO BOTH TABLES }
Any help would be appreciated.
http://msdn.microsoft.com/library/bb510625(v=sql.100).aspx
You use Table1 for target table and Table2 for source table
You want to do action, when given ID is not found in Table2 - in the source table
In the documentation, that you had read already, that corresponds to the clause
WHEN NOT MATCHED BY SOURCE ... THEN <merge_matched>
and the latter corresponds to
<merge_matched>::=
{ UPDATE SET <set_clause> | DELETE }
Ergo, you cannot insert into source-table there.
You could use triggers for auto-insertion, when you insert something in Table1, but that will not be able to insert proper Shared_Name - trigger just won't know it.
So you have two options i guess.
1) make T-SQL code block - look for Stored Procedures. I think there also is a construct to execute anonymous code block in MS SQ, like EXECUTE BLOCK command in Firebird SQL Server, but i don't know it for sure.
2) create updatable SQL VIEW, joining Table1 and Table2 to show last most current date, so that when you insert a row in this view the view's on-insert trigger would actually insert rows to both tables. And when you would update the data in the view, the on-update trigger would modify the data.

Copying data from old database to new one with a new structure

I had an old database with a single table containing customer orders and customer details. I went on to create a new database model using seperate tables for customers and details. I managed to migrate the customer details to the new database, but was unable to migrate the the cusomer orders. We thought that this would be ok, and that we would just build the order record from now on ignoring all previous orders in the old database. This was a while ago, and I cannot remember the exact reason why I was unable to import the customer orders. However, now we have discovered that we will need the old orders in the new database. Is there an easy way to do this using Microsoft Access?
This is the reason why:
Split a table in access into two linked tables
Depending on how complex your schema is, a simple approach would be schema-mapping by a INSERT INTO SELECT query.
For example if your old database had a table:
Orders
------
OrdID
CustID
ProductName
Price
oDay
oMonth
oYear
And your new database had fields with different names, extra fields, etc:
OrderDetails
------
Order_ID
Customer_ID
Product
Price
DeliveryAddress
OrderDate
All you would need to do was to create an insert query to append the old records to the new table. In defining the query, you can specify the source and destination field names, and you can even perform functions / expressions on the data. You can even query on the other table directly, without linking or importing it into your new database:
INSERT INTO OrderDetails (Order_ID,Customer_ID,Product,Price,OrderDate)
SELECT OrdID,CustID,ProductName,Price,DateSerial(oYear,oMonth,oDay) AS oDate
FROM Orders IN 'C:\oldDatabasePath.mdb';
If you have to do additional transformations to the data, such as run expressions on column values, I would recommend testing out the SELECT part of the query before adding the INSERT line.

Copy table data and populate new columns

So I'm trying to copy some data from database table to another. The problem is though, the target database table has 2 new columns that are required. I wanted to use the export/import wizard on SQL Server Management Studio but if I use that I will need to write a query for each table and I can only execute 1 query at a time. Was wondering if there are a more efficient way of doing it.
Here's an example of 1 table:
dbase1.dbo.Appointment { id, name, description, createdate }
dbase2.dbo.Appointment { id, name, description, createdate, auditby, auditat}
I have a total of 8 tables with those 2 additional columns. and most of them are related to each other via fk, so I wanted to use the wizard as it figures out which table gets inserted first. The problem with that is, it only works if I do a "copy data from one or more tables " and not the "write a query to specify data" (I use this to populate those two new columns).
I've been doing this very slow process in copying data as I'm using MVC Code First for my application and I dont have access to the server to be able to drop and create the table at my leisure. So I have to resort to this to maintain the data that I already have.
An idea: temporarily disable the foreign key constraints in the destination database. Then it doesn't matter what order you run your inserts. In order to populate the two new and required columns, you just need to pick some stock values to put in there (since obviously these rows initially are not subject to initial auditing). For example:
INSERT dbase2.dbo.appointment
(id, name, description, createdate, auditby, auditat)
SELECT id, name, description, createdate,
auditby = 'me', auditat = GETDATE()
FROM dbo.appointment;
Since it seems the challenge is merely that the destination requires columns that aren't in the source, and that you need to determine what should be populated in these audit columns, this seems to solve multiple problems at once. You just need to figure out what to put in there instead of 'me' and GETDATE().
(To get the wizard to pull these 8 tables for you, you might be able to create a view similar to the select portion of the above query, but that's more work and it won't see the underlying FK constraints to generate them in the right order anyway.)
Write the sql query for each of the insert processes in the order you want it. That would be the simplest approach.
Set the Default values for these two columns
Like for AuditAt - Default Date i.e. GetDate()
For AuditBy - The Person ID/Name
Now, you can Insert into these tables without entering for these two columns

table relationships, SQL 2005

Ok I have a question and it is probably very easy but I can not find the solution.
I have 3 tables plus one main tbl.
tbl_1 - tbl_1Name_id
tbl_2- tbl_2Name_id
tbl_3 - tbl_3Name_id
I want to connect the Name_id fields to the main tbl fields below.
main_tbl
___________
tbl_1Name_id
tbl_2Name_id
tbl_3Name_id
Main tbl has a Unique Key for these fields and in the other table, fields they are normal fields NOT NULL.
What I would like to do is that any time when the record is entered in tbl_1, tbl_2 or tbl_3, the value from the main table shows in that field, or other way.
Also I have the relationship Many to one, one being the main tbl of course.
I have a feeling this should be very simple but can not get it to work.
Take a look at SQL Server triggers. This will allow you to perform an action when a record is inserted into any one of those tables.
If you provide some more information like:
An example of an insert
The resulting change you would like
to see as a result of that insert
I can try and give you some more details.
UPDATE
Based on your new comments I suspect that you are working with a denormalized database schema. Below is how I would suggest you structure your tables in the Employee-Medical visit scenario you discussed:
Employee
--------
EmployeeId
fName
lName
EmployeeMedicalVisit
--------------------
VisitId
EmployeeId
Date
Cost
Some important things:
Note that I am not entering the
employees name into the
EmployeeMedicalVisit table, just the EmployeeId. This
helps to maintain data integrity and
complies with First Normal Form
You should read up on 1st, 2nd and
3rd normal forms. Database
normalization is a very imporant
subject and it will make your life
easier if you can grasp them.
With the above structure, when an employee visited a medical office you would insert a record into EmployeeMedicalVisit. To select all medical visits for an employee you would use the query below:
SELECT e.fName, e.lName
FROM Employee e
INNER JOIN EmployeeMedicalVisit as emv
ON e.EployeeId = emv.EmployeeId
Hope this helps!
Here is a sample trigger that may show you waht you need to have:
Create trigger mytabletrigger ON mytable
For INSERT
AS
INSERT MYOTHERTABLE (MytableId, insertdate)
select mytableid, getdate() from inserted
In a trigger you have two psuedotables available, inserted and deleted. The inserted table constains the data that is being inserted into the table you have the trigger on including any autogenerated id. That is how you get the data to the other table assuming you don't need other data at the same time. YOu can get other data from system stored procuders or joins to other tables but not from a form in the application.
If you do need other data that isn't available in a trigger (such as other values from a form, then you need to write a sttored procedure to insert to one table and return the id value through an output clause or using scope_identity() and then use that data to build the insert for the next table.

Resources