I'm having issues with the ALTER TABLE function - sql

I'm attempting to use the tables trip, guide and reservation in order to make a normalized table. I'm getting the error "ORA-00933: SQL command not properly ended."
I'm not certain what is wrong with ALTER TABLE.
SELECT trip.TRIP_ID, trip.State, trip.Max_grp_size, trip.type, trip.season, guide.Guide_num, guide.last_name, guide.First_name, guide.address, guide.city, guide.Hire_date, trip_guides.guide_num, reservations.trip_price
FROM trip
JOIN trip_guides ON trip.TRIP_ID = trip_guides.trip_id
JOIN Guide ON trip_guides.guide_num = guide.Guide_num
ALTER TABLE trip ADD (price_trip CHAR)
JOIN reservations ON trip.price_trip = reservations.trip_price
ORDER BY trip.trip_ID;

It sounds like what you want is a "CREATE TABLE ... AS (SELECT...)" type of statement. Essentially creating a NEW table based on the result set of a SQL statement.
This would look like:
CREATE TABLE your_1st_level_normalized_table AS
(
SELECT trip.TRIP_ID,
trip.STATE,
trip.Max_grp_size,
trip.type,
trip.season,
guide.Guide_num,
guide.last_name,
guide.First_name,
guide.address,
guide.city,
guide.Hire_date,
trip_guides.guide_num,
reservations.trip_price,
NULL as PRICE_TRIP /*new field in the new table set to NULL*/
FROM trip
JOIN trip_guides ON trip.TRIP_ID = trip_guides.trip_id
JOIN Guide ON trip_guides.guide_num = guide.Guide_num
JOIN reservations ON trip.price_trip = reservations.trip_price
);
I've removed the ORDER BY since that's not allowed in this statement.

Related

SQL merge statement with Joins

I am trying to use a merge statement for upsert operation. I want to do something like below where I join the both target and source table to the Student table for a unique key that only exists in the student table. Just to keep in mind, I cannot join StudentID. There could be a duplicate in my code. I need to join the schoolID for uniqueness.
Merge into GuardianTo gto inner join StudentTo sto on gto.fkStudentId = sto.StudentID
Using (Select * from GuardianFrom gfrom inner join StudentFrom sfrom on gfrom.fkStudentId = sfrom.StudentID) from
ON gto.guardianId = from.guardianId and sto.SchoolID = from.SchoolID
When....
I need to join the target guardianTo table with studentTo table to get the unique key of SchoolID. and match this ID with From tables. I know that this could be done in a separate insert and update statement (not merge), but is there a way to do something like the above using merge statement?
If you are using MSSQL you can do a merge like the code below. You need to supply a list of column names to use from your source query and then update/insert the columns you need in your target table (GuardianTo).
Merge into GuardianTo gto
Using (Select * from GuardianFrom gfrom inner join StudentFrom sfrom on gfrom.fkStudentId = sfrom.StudentID ) AS source (<column names in GuardianFrom, Studentfrom go here> )
ON (gto.guardianId = source.guardianId and gto.SchoolID = source.SchoolID)
WHEN MATCHED THEN
UPDATE SET <column in GuardianTo>= source.<column from source above> /* add any additional columns to update here*/
WHEN NOT MATCHED THEN
INSERT (guardianId, SchoolID, StudentID /* add any additional columns to insert here*/)
VALUES (source.guardianId, source.SchoolID, source.StudentID /* add any additional columns from the source to insert here*/);

What if the column to be indexed is nvarchar data type in SQL Server?

I retrieve data by joining multiple tables as indicated on the image below. On the other hand, as there is no data in the FK column (EmployeeID) of Event table, I have to use CardNo (nvarchar) fields in order to join the two tables. On the other hand, the digit numbers of CardNo fields in the Event and Employee tables are different, I also have to use RIGHT function of SQL Server and this makes the query to be executed approximately 10 times longer. So, in this scene what should I do? Can I use CardNo field without changing its data type to int, etc (because there are other problem might be seen after changing it and it sill be better to find a solution without changing the data type of it). Here is also execution plan of the query below.
Query:
; WITH a AS (SELECT emp.EmployeeName, emp.Status, dep.DeptName, job.JobName, emp.CardNo
FROM TEmployee emp
LEFT JOIN TDeptA AS dep ON emp.DeptAID = dep.DeptID
LEFT JOIN TJob AS job ON emp.JobID = job.JobID),
b AS (SELECT eve.EventID, eve.EventTime, eve.CardNo, evt.EventCH, dor.DoorName
FROM TEvent eve LEFT JOIN TEventType AS evt ON eve.EventType = evt.EventID
LEFT JOIN TDoor AS dor ON eve.DoorID = dor.DoorID)
SELECT * FROM b LEFT JOIN a ON RIGHT(a.CardNo, 8) = RIGHT(b.CardNo, 8)
ORDER BY b.EventID ASC
You can add a computed column to your table like this:
ALTER TABLE TEmployee -- Don't start your table names with prefixes, you already know they're tables
ADD CardNoRight8 AS RIGHT(CardNo, 8) PERSISTED
ALTER TABLE TEvent
ADD CardNoRight8 AS RIGHT(CardNo, 8) PERSISTED
CREATE INDEX TEmployee_CardNoRight8_IDX ON TEmployee (CardNoRight8)
CREATE INDEX TEvent_CardNoRight8_IDX ON TEvent (CardNoRight8)
You don't need to persist the column since it already matches the criteria for a computed column to be indexed, but adding the PERSISTED keyword shouldn't hurt and might help the performance of other queries. It will cause a minor performance hit on updates and inserts, but that's probably fine in your case unless you're importing a lot of data (millions of rows) at a time.
The better solution though is to make sure that your columns that are supposed to match actually match. If the right 8 characters of the card number are something meaningful, then they shouldn't be part of the card number, they should be another column. If this is an issue where one table uses leading zeroes and the other doesn't then you should fix that data to be consistent instead of putting together work arounds like this.
This line is what is costing you 86% of the query time:
LEFT JOIN a ON RIGHT(a.CardNo, 8) = RIGHT(b.CardNo, 8)
This is happening because it has to run RIGHT() on those fields for every row and then match them with the other table. This is obviously going to be inefficient.
The most straightforward solution is probably to either remove the RIGHT() entirely or else to re-implement it as a built-in column on the table so it doesn't have to be calculated on the fly while the query is running.
While inserting the record, you would have to also insert the eight, right digits of the card number and store it in this field. My original thought was to use a computed column but I don't think those can be indexed so you'd have to use a regular column.
; WITH a AS (
SELECT emp.EmployeeName, emp.Status, dep.DeptName, job.JobName, emp.CardNoRightEight
FROM TEmployee emp
LEFT JOIN TDeptA AS dep ON emp.DeptAID = dep.DeptID
LEFT JOIN TJob AS job ON emp.JobID = job.JobID
),
b AS (
SELECT eve.EventID, eve.EventTime, eve.CardNoRightEight, evt.EventCH, dor.DoorName
FROM TEvent eve LEFT JOIN TEventType AS evt ON eve.EventType = evt.EventID
LEFT JOIN TDoor AS dor ON eve.DoorID = dor.DoorID
)
SELECT *
FROM b
LEFT JOIN a ON a.CardNoRightEight = b.CardNoRightEight
ORDER BY b.EventID ASC
This will help you see how to add a calculated column to your database.
create table #temp (test varchar(30))
insert into #temp
values('000456')
alter table #temp
add test2 as right(test, 3) persisted
select * from #temp
The other alternative is to fix the data and the data entry so that both columns are the same data type and contain the same leading zeros (or remove them)
Many thanks all of your help. With the help of your answers, I managed to reduce the query execution time from 2 minutes to 1 at the first step after using computed columns. After that, when creating an index for these columns, I managed to reduce the execution time to 3 seconds. Wow, it is really perfect :)
Here are the steps posted for those who suffers from a similar problem:
Step I: Adding computed columns to the tables (As CardNo fields are nvarchar data type, I specify data type of computed columns as int):
ALTER TABLE TEvent ADD CardNoRightEight AS RIGHT(CAST(CardNo AS int), 8)
ALTER TABLE TEmployee ADD CardNoRightEight AS RIGHT(CAST(CardNo AS int), 8)
Step II: Create index for the computed columns in order to execute the query faster:
CREATE INDEX TEmployee_CardNoRightEight_IDX ON TEmployee (CardNoRightEight)
CREATE INDEX TEvent_CardNoRightEight_IDX ON TEvent (CardNoRightEight)
Step 3: Update the query by using the computed columns in it:
; WITH a AS (
SELECT emp.EmployeeName, emp.Status, dep.DeptName, job.JobName, emp.CardNoRightEight --emp.CardNo
FROM TEmployee emp
LEFT JOIN TDeptA AS dep ON emp.DeptAID = dep.DeptID
LEFT JOIN TJob AS job ON emp.JobID = job.JobID
),
b AS (
SELECT eve.EventID, eve.EventTime, evt.EventCH, dor.DoorName, eve.CardNoRightEight --eve.CardNo
FROM TEvent eve
LEFT JOIN TEventType AS evt ON eve.EventType = evt.EventID
LEFT JOIN TDoor AS dor ON eve.DoorID = dor.DoorID)
SELECT * FROM b LEFT JOIN a ON a.CardNoRightEight = b.CardNoRightEight --ON RIGHT(a.CardNo, 8) = RIGHT(b.CardNo, 8)
ORDER BY b.EventID ASC

How to create a table with multiple columns

Struggling with a create table statement which is based on this select into statement below:
#MaxAPDRefundAmount money = 13.00
...
select pkd.*, pd.ProviderReference, per.FirstName, per.Surname, #MaxAPDRefundAmount [MaxAPDRefundAmount],commission.Type [Commission] into #StagedData from CTE_PackageData pkd
inner join J2H.dbo.Package pk on pkd.Reference = pk.Reference
inner join J2H.dbo.Product pd on pk.PackageId = pd.PackageId
inner join J2H.dbo.FlightReservation fr on pd.ProductId = fr.ProductId
and fr.FlightBoundID = 1
inner join J2H.dbo.ProductPerson pp on pd.ProductId = pp.ProductID
and pp.StatusId < 7
inner join J2H.dbo.Flight f on fr.FlightId = f.FlightID
inner join J2H.dbo.Person per on pk.PackageId = per.PackageId
and per.PersonId = pp.PersonId
inner join J2H.dbo.PersonType pt on per.PersonTypeId = pt.PersonTypeID
We are changing a select into to just normal insert and select, so need a create table (we are going to create a temp (hash tag table) and not declaring a variable table. Also there is a pkd.* at the start as well so I am confused in knowing which fields to include in the create table. Do I include all the fields in the select statement into the create statement?
Update:
So virtually I know I need to include the data types below but I can just do:
create table #StagedData
(
pkd.*,
pd.ProviderReference,
per.FirstName,
per.Surname,
#MaxAPDRefundAmount [MaxAPDRefundAmount],
commission
)
"Do I include all the fields in the select statement into the create statement?" Well, that depends, if you need them, than yes, if not than no. It's impossible for us to say whether you need them... If you're running this exact query as insert, than yes.
As for the create statement, you can run the query you have, but replace into #StagedData with something like into TEMP_StagedData. In management studio you can let sql server build the create query for you: right-click the newly created TEMP_StagedData table in the object explorer (remember to refresh), script Table as, CREATE To and select New Query Editor Window.
The documentation of the CREATE TABLE statement is pretty straightforward.
No. Clearly, you cannot use pkd.* in a create table statement.
What you can do is run your old SELECT INTO statement as a straight SELECT (remove the INTO #stagedata) part, and look at the columns that get returned by the SELECT.
Then write a CREATE TABLE statement that includes those columns.
To create a table from a SELECT without inserting data, add a WHERE clause that never returns True.
Like this:
SELECT * INTO #TempTable FROM Table WHERE 1=0
Once the table with the columns for your SELECT, you can add additional columns with ALTER TABLE.
ALTER TABLE #TempTable ALL ExtraColumn INT
Then do your INSERT/SELECT.

Update database from another using joins?

I am trying to update a table from another database using joins and having a hard time. This is what I am trying to do in pseudo:
UPDATE [Database1].[dbo].[Sessions]
SET [SpeakerID] = ?STATEMENT1?
WHERE ?STATEMENT2?
For "Statement1", this would be coming from another database and table that has columns: SessionID and SpeakerID. How can this be achieved?
UPDATE a
SET a.SpeakerID = b.colName -- SET valoue here
FROM Database1.dbo.Sessions a
INNER JOIN Database2.dbo.Sessions b
ON a.SessionID = b.SessionID -- assumes that their
-- relationship column is SessionID,
-- change it in your original columnName
WHERE ....
a and b are called alias. They are useful when you have longer source name.
UPDATE L
SET SpeakerID = R.SpeakerID
FROM dbo.LocalTable AS L
INNER JOIN RemoteDatabase.dbo.RemoteTable AS R
ON L.SomeValue = R.SomeValue;
This really is no different from this problem except you have to add a database prefix to one of the tables in the join.
try
UPDATE [Database1].[dbo].[Sessions]
SET
Sessions.col1 = other_table.col1
FROM
[Database1].[dbo].[Sessions] Sessions
INNER JOIN
[Database2].[dbo].other_table AS other_table
ON
Sessions.id = other_table.id
WHERE Sessions.id = ??
Note if the database is on another server you will need to create a linked server first
http://msdn.microsoft.com/en-us/library/ff772782.aspx

SQL saving to a Temporary table is not working

i have the following sql query
SELECT P.catalogid,
Sum(numitems) numitems,
Sum(ignoreditems) ignoreditems,
P.supplierid,
P.cname,
P.cprice,
P.cstock,
P.ccode,
P.minstock,
P.pother4,
P.processedsucssessfully,
P.notprocessed,
Y.backorder
INTO ##tempt
FROM ##temporderstable P
JOIN supporder Y
ON P.catalogid = Y.catalogid
GROUP BY P.catalogid,
P.supplierid,
P.cname,
P.cprice,
P.cstock,
P.ccode,
P.minstock,
P.pother4,
Y.backorder,
P.processedsucssessfully,
P.notprocessed
i am trying to save the result of join into another temporty table, but when i try to access the new table from another query it says invalid object name, is this the right way to save the result of this query to ##tempt?
Try using explicit temp table declaration and then check!!
Like this
CREATE TABLE ##tempt (
supplierid int,
other fields ..)