Populate a column in a junction table Transact-SQL - sql-server

I have two tables with a many-to-many relationship.
The relevant part of the tables look like this:
Filmlager [ProgramID, Type]
Genre [GenreID, GenreTitle]
Since there's a many-to-many relationship I've created a junction table looking like this:
ProgramGenre [ProgramID, GenreID, GenreOrder]
Now I want to set the value 1 in the GenreOrder column where Filmlager.Type=Genre.GenreTitle
So far I've managed to get the ProgramID and GenreID where I want to update the GenreOrder by using the following query:
SELECT p.ProgramID, p.GenreID
FROM ProgramGenre p, Filmlager f, Genre g
WHERE p.ProgramID = f.ProgramID
AND p.GenreID = g.GenreID
AND f."Type"= g.GenreTitle;
I'm not sure how to proceed from here. The part I can't figure out is how to compare the combination of two columns (the result from the query above) with ProgramID and GenreID in the ProgramGenre table. I've tried using nested queries without success.
I'm using Transact-SQL in Microsoft SQL Server Management Studio
Thanks in advance!

Just do an update:
UPDATE p SET GenreOrder = 1
FROM ProgramGenre p
JOIN Filmlager f ON p.ProgramID = f.ProgramID
JOIN Genre g ON p.GenreID = g.GenreID
WHERE f."Type"= g.GenreTitle;

Related

transfer data from one database to another regarding keys

How can i transfer rows from two tables (Patient and ContactDetails) from DB1 to DB2?
Both DBs, have already these 2 tables with data. i just want to add data from these two tables from db1 to db2.
i tried following that
but it didnt work, because there are some rows with the same keys and overwrite is forbidden.
is there an other way to do it? or am i missing something?
patient and contactdetails relationship is
patient inner join contactdetails
(foreign_key)patient.contactdetailsid = (primary_key)contactdetails.id
loop on the source contactdetails table, insert each row one a time saving in a temp table the old contactdetail id and the matching new contactdetail id (here is an example of sql loop).
the temp table should be something like:
create #temptableforcopy table (
oldcontactdetailsid [insertheretherightdatatype],
newcontactdetailsid [insertheretherightdatatype]
)
copy the data from the patient table joined to the temp table used for the previous step like this:
insert into newdb.newschema.patient (contactdetailsid, field1, field2, ...)
select TT.newcontactdetailsid,
old.field1,
old.field2,
...
from olddb.oldschema.patient old
join #temptableforcopy TT on TT.oldcontactdetailsid = old.contactdetailsid
please note that my proposal is just a wild guess: you gave no information about structure, keys, constraints, no detail about which key is preventing the copy with which error message, the solution you already discarded, the amount of data you have to deal with...

View showing incorrect data

I have a very simple database. It contains 3 tables. The first is the primary input table where values go in. The 2nd and 3rd are there purely for translating values to names for a view. When I view the rows in table 1, I can see that column businessUnit contains valid values in all rows. When I add the Business_Units table (The 3rd table in this DB), all but 2 rows go away and despite the businessUnit value both being 1 in the 1st table, the view gives them different names.
I created a DB diagram and uploaded a screenshot to imgur. Link: http://imgur.com/jXF7L1R
I only have 2 relationships in the table. One from equipType on New_Equipment_User to id in Equipment_Type and one from businessUnit in New_Equipment_User to id in Business_Units. The weird thing is that the Equipment Type works perfectly, yet when I replicate the table, relationship and view information exactly, it doesn't work. Instead of 6 rows appearing, there are only 2 which share the same value in businessUnit, but gives 2 different names for it.
In case it matters, here is my view Query:
SELECT dbo.New_Equipment_User.id, dbo.Equipment_Type.name AS equipType, dbo.New_Equipment_User.jobNumber, dbo.New_Equipment_User.costCode,
dbo.New_Equipment_User.reason, dbo.New_Equipment_User.mobile, dbo.New_Equipment_User.mobileQty, dbo.New_Equipment_User.mobileComment,
dbo.New_Equipment_User.laptop, dbo.New_Equipment_User.laptopQty, dbo.New_Equipment_User.laptopComment, dbo.New_Equipment_User.desktop,
dbo.New_Equipment_User.desktopQty, dbo.New_Equipment_User.desktopComment, dbo.New_Equipment_User.modem, dbo.New_Equipment_User.modemQty,
dbo.New_Equipment_User.modemComment, dbo.New_Equipment_User.printer, dbo.New_Equipment_User.printerQty, dbo.New_Equipment_User.printerComment,
dbo.New_Equipment_User.camera, dbo.New_Equipment_User.cameraQty, dbo.New_Equipment_User.cameraComment, dbo.New_Equipment_User.dateRequired,
dbo.New_Equipment_User.requestedBy, dbo.New_Equipment_User.dateRequested, dbo.New_Equipment_User.approvalStatus,
dbo.Business_Units.name AS businessUnit
FROM dbo.New_Equipment_User
JOIN dbo.Equipment_Type ON dbo.New_Equipment_User.equipType = dbo.Equipment_Type.id
JOIN dbo.Business_Units ON dbo.New_Equipment_User.id = dbo.Business_Units.id
WHERE (dbo.New_Equipment_User.approvalStatus = '0')
And here is an image of the view since it is easier to read: http://imgur.com/pZ97ehQ
Is anyone able to assist with why this might be happening?
Try using a LEFT JOIN
SELECT ...
FROM dbo.New_Equipment_User
JOIN dbo.Equipment_Type ON dbo.New_Equipment_User.equipType = dbo.Equipment_Type.id
LEFT JOIN dbo.Business_Units ON dbo.New_Equipment_User.id = dbo.Business_Units.id
This will ensure that all dbo.New_Equipment_User and all dbo.Equipment_Type is present

Selecting multiple rows of many to many related columns into one column in SQL SERVER?

I have the following DB Tables with SQL Server
Booking(bookingID,customerName,branchID,RefNumber,...)
Trip(TripID,vehicleID,...)
BookingToTripMap(TripID,bookingID)
Branch(branchID, branchName)
Vehicle(vehicleID,vehicleNumber)
There is a one to one relationship between (Booking,Branch) and (Trip, Vehicle) and Many to many relationship between Booking, Trip which is saved in the table BookingToTripMap.
Now I want to extract a query that would return the following
Booking.RefNumber Booking.CustomerName Vehicle.VehicleNumber
(All vehicle numbers in one cell)
Here is your query
SELECT B.RefNumber, B.CustomerName, V.VehicleNumber
FROM ((Booking AS B INNER JOIN BookingToTripMap AS BT
ON B.bookingID = BT.bookingID) INNER JOIN TRIP as T
ON T.TripID = BT.TripID) INNER JOIN Vehicle as V
ON V.vehicleID = T.vehicleID
I would add the field bookingID to the table Trip, it seems that the table BookingToTripMap doesn't add any value to your database.
Also, if your vehicle's numbers are unique, you could change the primary key in the Vehicle table to vehicleNumber, and change the same columns in the Trip table. Thus you could retrieve the vehicleNumber directly from the Trip table.
I'm just guessing in that, based on the given information.
Regards,

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.

SQL Pivot Table for Many-To-Many Relationship for use in SSRS

Using SQL Server 2008, I am trying to figure out how to create a query that returns a pivot table with a standard many-to-many relationship. This relationship defines which users belong to which roles and I want the table to list the user name along the side and the role names across the top. The ultimate goal is to have this output in SQL Server Reporting Services, so it doesn't matter if SQL server generates the pivot results, or SSRS generates the results (is one method better than the other?). Here is my sample schema:
Users Table:
UserID
UserName
Rights Table:
RightID
RightName
RightsMembership Table:
UserID
RightID
I want the following output as a report in SSRS. Any help is appreciated.
RightOne RightTwo RightThree RightFour
jdoe X X
mjane X X
ssmith X X X
FYI: Roles can be added, so I would prefer not to have to hard code the role name or count in the query.
I Don't Know about the Pivot Tables but you can achieve this in the SSRS as below
Select UserName,
RightName
From users u INNER JOIN RightMembership rm on rm.UserID = u.UserID
INNER JOIN Rights r on rm.RightID = r.RightID
Use this query as the Stored Procedure or Query and the Order By Accordingly and
Create the Dataset and Datasource
Insert matrix in the report
In the rows select the UserName field From the Created Dataset
In the columns select the RightName field from the created Dataset
In the Data use this Expression below then you will get the desired output
=IIF(Fields!UserName.Value = nothing,nothing,"X") As the Data in the matrix

Resources