select sql statement... error with from clause - sql

Table 1: Students
Name Class PK
John Mike 1
Andrei Tom 2
Table 2: Grades
Disciplne Grade PK_student
math 2 1
math 10 1
math 8 2
math 5 2
What it's the correct statement to delete rows in table 2 grades by PK from students. My point it's to delete a studente from databse and his grades. Thanks
i try to delete in c# grades for a student. I read name and second name, and it should remove his grades from table
OleDbCommand comanda1 = new OleDbCommand("DELETE FROM GRADES WHERE PK_student=SELECT PK FROM Students WHERE Name=#p0 AND Class=#p1 ; ", conex);
comanda1.Parameters.Add(new OleDbParameter("p0", v[0]));
omanda1.Parameters.Add(new OleDbParameter("p1", v[1]));
it gives me an error in FROM clause.

If you want to delete the data rfom table 2 by table 1 then you can use following query:
DELETE FROM GRADES WHERE PK_student IN (SELECT PK FROM STUDENTS);
Hope this is the desired query you want to achieve.

Related

On Statement Self Join

I am having trouble wrapping my head around the on statement when doing a self-join. Let's say we have the following table:
employeeid
name
managerid
salary
1
Mike
3
35000
2
Rob
1
45000
3
Todd
NULL
25000
4
Ben
1
55000
5
Sam
1
65000
I want to perform a self join to return the employee name and their manager's name.
When I perform the following self join I get an incorrect result:
SELECT E.name as Employee,M.name as Manager
FROM tblEmployees E
LEFT JOIN tblEmployees M
ON E.Employeeid=M.managerid
However, when I reverse the columns on the on statement using the query below:
SELECT E.name as Employee,M.name as Manager
FROM tblEmployees E
LEFT JOIN tblEmployees M
ON E.managerid=M.Employeeid
I get the correct answer.
Why? How do I know which columns to select in an on statement?
Here's my explanation:
The table you have is structured with each row representing an employee in the company.
You are interested in determining who is each employee's manager.
You are able to find that by joining the table on itself where the lookup values are the manager ids (managerid) and the reference column are the employee ids (employeeid).
The first query is wrong because the employeeid column is being used for the lookup values and the managerid column is being used for reference.
To get the manager of each employee you need to look use the managerid column as the lookup column and the employeeid column as the reference column.
Hope that's not too confusing!

Insert values from one table to another if certain columns are unique from different databases

The setup I have is the following I have to databases A and B on the same server.
A and B have identical table names. I want to append data from tables of A to tables of B. However I want to append a certain row from A to B if and only if that row is unique on certain fields. For instance if i have table named People.
in A
People:
ID name Surname
1 Mark Anthony
2 Julius Ceasar
3 Marcus Crassus
in B
People
ID name Surname
1 Marcus Caelius
2 Julius Ceasar
3 Sevilius Casca
4 Marcus Crassus
I want to add to the People table in B database those rows of People table in A where the name and surname fields do not already exist People of B.
so the result would be
in B
People
ID name Surname
1 Marcus Caelius
2 Julius Ceasar
3 Sevilius Casca
4 Marcus Crassus
5 Mark Anthony
I think this is just an insert . . . select:
insert into b.people(name, surname)
select name, surname
from a.people a
where not exists (select 1 from b.people b where b.name = a.name and b.surname = a.surname);
This assumes that the id field is a serial/identity/auto increment column. That is a best practice anyway.
You can also write this as:
insert into b.people(name, surname)
select name, surname
from a.people a
except
select name, surname
from b.people b;

SQL Insert with value from different table

I have 2 tables storing information. For example:
Table 1 contains persons:
ID NAME CITY
1 BOB 1
2 JANE 1
3 FRED 2
The CITY is a id to a different table:
ID NAME
1 Amsterdam
2 London
The problem is that i want to insert data that i receive in the format:
ID NAME CITY
1 PETER Amsterdam
2 KEES London
3 FRED London
Given that the list of Cities is complete (i never receive a city that is not in my list) how can i insert the (new/received from outside)persons into the table with the right ID for the city?
Should i replace them before I try to insert them, or is there a performance friendly (i might have to insert thousands of lines at one) way to make the SQL do this for me?
The SQL server i'm using is Microsoft SQL Server 2012
First, load the data to be inserted into a table.
Then, you can just use a join:
insert into persons(id, name, city)
select st.id, st.name, c.d
from #StagingTable st left join
cities c
on st.city = c.name;
Note: The persons.id should probably be an identity column so it wouldn't be necessary to insert it.
insert into persons (ID,NAME,CITY) //you dont need to include ID if it is auto increment
values
(1,'BOB',(select Name from city where ID=1)) //another select query is getting Name from city table
if you want to add 1000 rows at a time that'd be great if you use stored procedure like this link

Insert trigger on a table with extra constant column in to new table?

I've been working on a database which consists of two schemas names as front and backup. Where in one table name:
front.Details
studID SemID GPA
100 1 4
200 2 3
Another table name is:
backup.DetailsV
studID DEPT SemID GPA
The output in Table backup.DetailsV should look like below:
studID DEPT SemID GPA
100 1 1 4
200 1 2 3
100 2 1 4
200 2 2 3
How can I create trigger on table Details to insert in to table DetailsV twice with dept id 1 and 2?
To continue Damien's thought, if the only reason to have the DetailsV table is to generate that output, you can easily do that with a view. If it is just reading data, the stored procedure doesn't know or care if the source is a table or a view.
Select studID, 1 as Dept, SemID, GPA
From front.Details
UNION ALL
Select studID, 2 as Dept, SemID, GPA
From front.Details
You would only keep a backup table if you needed to keep a history of the data flowing through the front.Details table, or if you needed to manipulate that data before reporting it out. If that is really what you want, the trigger query is very similar, but instead of addressing the table, you use the special [inserted] table to get the new values.
Select studID, 1 as Dept, SemID, GPA
From inserted
UNION ALL
Select studID, 2 as Dept, SemID, GPA
From inserted

UPDATE query that fixes orphaned records

I have an Access database that has two tables that are related by PK/FK. Unfortunately, the database tables have allowed for duplicate/redundant records and has made the database a bit screwy. I am trying to figure out a SQL statement that will fix the problem.
To better explain the problem and goal, I have created example tables to use as reference:
alt text http://img38.imageshack.us/img38/9243/514201074110am.png
You'll notice there are two tables, a Student table and a TestScore table where StudentID is the PK/FK.
The Student table contains duplicate records for students John, Sally, Tommy, and Suzy. In other words the John's with StudentID's 1 and 5 are the same person, Sally 2 and 6 are the same person, and so on.
The TestScore table relates test scores with a student.
Ignoring how/why the Student table allowed duplicates, etc - The goal I'm trying to accomplish is to update the TestScore table so that it replaces the StudentID's that have been disabled with the corresponding enabled StudentID. So, all StudentID's = 1 (John) will be updated to 5; all StudentID's = 2 (Sally) will be updated to 6, and so on. Here's the resultant TestScore table that I'm shooting for (Notice there is no longer any reference to the disabled StudentID's 1-4):
alt text http://img163.imageshack.us/img163/1954/514201091121am.png
Can you think of a query (compatible with MS Access's JET Engine) that can accomplish this goal? Or, maybe, you can offer some tips/perspectives that will point me in the right direction.
Thanks.
The only way to do this is through a series of queries and temporary tables.
First, I would create the following Make Table query that you would use to create a mapping of the bad StudentID to correct StudentID.
Select S1.StudentId As NewStudentId, S2.StudentId As OldStudentId
Into zzStudentMap
From Student As S1
Inner Join Student As S2
On S2.Name = S1.Name
Where S1.Disabled = False
And S2.StudentId <> S1.StudentId
And S2.Disabled = True
Next, you would use that temporary table to update the TestScore table with the correct StudentID.
Update TestScore
Inner Join zzStudentMap
On zzStudentMap.OldStudentId = TestScore.StudentId
Set StudentId = zzStudentMap.NewStudentId
The most common technique to identify duplicates in a table is to group by the fields that represent duplicate records:
ID FIRST_NAME LAST_NAME
1 Brian Smith
3 George Smith
25 Brian Smith
In this case we want to remove one of the Brian Smith Records, or in your case, update the ID field so they both have the value of 25 or 1 (completely arbitrary which one to use).
SELECT min(id)
FROM example
GROUP BY first_name, last_name
Using min on ID will return:
ID FIRST_NAME LAST_NAME
1 Brian Smith
3 George Smith
If you use max you would get
ID FIRST_NAME LAST_NAME
25 Brian Smith
3 George Smith
I usually use this technique to delete the duplicates, not update them:
DELETE FROM example
WHERE ID NOT IN (SELECT MAX (ID)
FROM example
GROUP BY first_name, last_name)