Transfer data from one table to another in sql server - sql-server

I have two tables, one of which I don't need anymore. I want to transfer the piece of data i need from the obsolete table, into the table I'm going to keep. There are bookingid columns in both tables, which I can use to match the rows up. Its a 1 to 0 or 1 relationship. I've looked around and built up this query to accomplish the transfer, but I'm getting a could not be bound error on bookingtoupdate.bookingid
WITH bookingtoupdate (bookingid) AS
(
SELECT bookingid
FROM bookings
)
UPDATE bookings
SET meetinglocation = (SELECT business.name
FROM abk_Locations
INNER JOIN business ON dbo.abk_Locations.IP_Number = business.businessid
WHERE
(dbo.abk_Locations.Booking_Number = bookingtoupdate.bookingid)
)
WHERE
bookingid = bookingtoupdate.bookingid
Are there any obvious issues with my code?
I referred the following pages...
http://msdn.microsoft.com/en-us/library/ms175972.aspx
SQL Server FOR EACH Loop

You declare bookingtoupdate but you don't select anything from it. That's why it can't be bound.
Here is a simplified query to do what you need without CTE
UPDATE bookings
SET meetinglocation = business.name
FROM bookings
INNER JOIN abk_Locations ON abk_Locations.Booking_Number = bookings.bookingid
INNER JOIN business ON dbo.abk_Locations.IP_Number = business.businessid

Related

Can I inner join a previous SQL query then perform counts

I've created a query from a fairly large database.
At the moment each single procedure undertaken by an employee appears as 3 identical timed rows Each row informs the site where procedure occurred, equipment part used and whether day or night.
I want to combine the rows with matching name and time together to create a single row containing all the other fields.
I then want to be able to create a log for the employee to show how many of each procedure has been undertaken and the site and technique used.
I figure an inner join may be the best way to do this but would be grateful for further help as to how to set this up on a sub-query.
Current query:
SELECT procedure, employee, chart_time, form,
FROM cust.records
WHERE employeeID IN () AND procedurelabel LIKE 'rad1'
Really appreciate the help
Your question could use a little clarification... not least being the DDL for your table and a few notes on what each column is. Nonetheless, assuming these rows are all in the cust.records table and that each set of 3 rows have a unique combination of name and time, you could do something like this...
SELECT -- first select fields common to all rows... may as well take these from the first table
records1.procedure, records1.employee, records1.chart_time,
-- ... then select records from your joins
records2.some_column,
records3.some_column
FROM cust.records records1
INNER JOIN WHERE cust.records records2 on records1.chart_time = records2.chart_time
and records1.procedure = record2.procedure
and records1.employee = records2.employee
-- Possible condition required here to not join this row to itself
-- or to explicitly join to a specific type of row
INNER JOIN WHERE cust.records records3 on records1.chart_time = records3.chart_time
and records1.procedure = record3.procedure
and records1.employee = records3.employee
-- Possible condition required here to not join this row to itself
-- or to explicitly join to a specific type of row
WHERE employeeID IN ()
AND procedurelabel LIKE 'rad1'
-- Possible condition required here specify the row to select for records1.
Might also be worth considering a table re-design since what you've described doesn't sound normalised.

Why does sql server do a scan on joins when there are no records in source table

The idea of the below query is to use the CTE to get the primary key of all rows in [Archive].[tia_tia_object] that meet the filter.
The execution time for the query within the CTE is 0 seconds.
The second part is supposed to do joins on other tables, to filter the data some more, but only if there are any rows returned in the CTE. This was the only way I could get the SQL server to use the correct indexes.
Why does it spend time (see execution plan) looking in TIA_TIA_AGREEMENT_LINE and TIA_TIA_OBJECT, when CTE returns 0 rows?
WITH cte_vehicle
AS (SELECT O.[Seq_no],
O.Object_No
FROM [Archive].[tia_tia_object] O
WHERE O.RECORD_TIMESTAMP >
(SELECT LastLoadTimeStamp FROM staging.Ufngetlastloadtimestamp('Staging.CoveredObject'))
AND O.[Meta_iscurrent] = 1
AND O.OBJECT_TYPE IN ( 'BIO01', 'CAO01', 'DKV', 'GFO01',
'KMA', 'KNO01', 'MCO01', 'VEO01',
'SVO01', 'AUO01' ))
SELECT O.[Seq_no] AS [Bkey_CoveredObject],
Cast(O.[Agr_Line_No] AS BIGINT) AS [Agr_Line_No],
O.[Cover_Start_Date] AS [CoverageFrom],
O.[Cover_End_Date] AS [CoverageTo],
O.[Timestamp] AS [TIMESTAMP],
O.[Record_Timestamp] AS [RECORD_TIMESTAMP],
O.[Newest] AS [Newest],
O.LOCATION_ID AS LocationNo,
O.[Cust_no],
O.[N01]
FROM cte_vehicle AS T
INNER JOIN [Archive].[tia_tia_object] O
ON t.Object_No = O.Object_No
AND t.Seq_No = O.Seq_No
INNER JOIN [Archive].[tia_tia_agreement_line] AL
ON O.Agr_line_no = AL.Agr_line_no
INNER JOIN [Archive].[tia_tia_policy] P
ON AL.Policy_no = P.Policy_no
WHERE P.[Transaction_type] <> 'D'
Execution plan:
Because it still needs to check and look for records. Even if there are no records in that table, it doesn't know that until it actually checks.
Much like if someone gives you a sealed box, you don't know it's empty or not till you open it.

SQL Joining journal tables to user tables

I have a MSSQL database with 3 tables: Journals, Customers, and UserAccounts.
I'm trying to query Journals for transactions per account manager. This table has a customer ID column that links to Customers.
The Customers table has a ACC_Manager column that links to UserAccounts via UserID.
Inside the UserAcounts table are first and last name columns.
So it would be
Select
Journal.amount,
Customer.name,
UserAccounts.first
From
Tables
where
Journal.ACC_manager = 'Matt'
I'm having issues joining the tables so I can query using UserAccounts.first. Could anybody help? Thanks
Try the following. I didn't get exact column names so don't just use this code without modifying it a bit to suit your specific needs:
SELECT
j.amount,
c.name,
u.first
FROM
Journals j
JOIN Customers c ON
c.customerID = j.customerID -- Exact column names?
JOIN UserAccounts u ON
u.UserID = c.ACC_Manager
WHERE
u.first = 'Matt'
You may also need to use LEFT JOIN as opposed to JOIN. Read up on JOINs to be sure.

Update Multiple records in single query MS SQL

I am trying to update multiple records in the table using the temporary table using the below query, but doesn't working. Please tell me the proper way to update multiple records.
UPDATE sarufoo
SET sarufoo.mobile = (SELECT mobile_no FROM logan)
WHERE sarufoo.homep IN (SELECT homep FROM logan);
One neater way to achieve that be would to join the two tables:
UPDATE sf
SET sf.mobile = l.mobile_no
From
sarufoo sf
JOIN logan l ON sf.homep = l.homep
You have to correlate the row you are updating with the row you are selecting from. Otherwise your subselect (the SET one) will return every row it has.
UPDATE sarufoo
SET sarufoo.mobile = (SELECT mobile_no FROM logan WHERE sarufoo.homep = logan.homep)
WHERE sarufoo.homep IN (SELECT homep FROM logan);

UPDATE query from OUTER JOINed tables or derived tables

Is there any way in MS-Access to update a table where the data is coming from an outer joined dataset or a derived table? I know how to do it in MSSQL, but in Access I always receive an "Operation must use updateable query" error. The table being updated is updateable, the source data is not. After reading up on the error, Microsoft tells me that the error is caused when the query would violate referential integrity. I can assure this dataset will not. This limitation is crippling when trying to update large datasets. I also read that this can supposedly be remedied by enabling cascading updates. If this relationship between my tables is defined in the query only, is this a possibility? So far writing the dataset to a temp table and then inner joining that to the update table is my only solution; that is incredibly clunky. I would like to do something along the lines of this:
UPDATE Table1
LEFT JOIN Table2 ON Table1.Field1=Table2.Field1
WHERE Table2.Field1 IS Null
SET Table1.Field1= Table2.Field2
or
UPDATE Table1 INNER JOIN
(
SELECT Field1, Field2
FROM Table2, Table3
WHERE Field3=’Whatever’
) AS T2 ON Table1.Field1=T2.Field1
SET Table1.Field1= T2.Field2
Update Queries are very problematic in Access as you've been finding out.
The temp table idea is sometimes your only option.
Sometimes using the DISTINCTROW declaration solves the problem (Query Properties -> Unique Records to 'Yes'), and is worth trying.
Another thing to try would be to use Aliases on your tables, this seems to help out the JET engine as well.
UPDATE Table3
INNER JOIN
(Table1 INNER JOIN Table2 ON Table1.uid = Table2.uid)
ON
(Table3.uid = Table2.uid)
AND
(Table3.uid = Table1.uid)
SET
Table2.field=NULL;
What I did is:
1. Created 3 tables
2. Establish relationships between them
3. And used the query builder to update a field in Table2.
There seems to be a problem in the query logic. In your first example, you LEFT JOIN to Table2 on Field1, but then have
Table2.Field1 IS NULL
in the WHERE clause. So, this limits you to records where no JOIN could be made. But then you try and update Table 1 with data from Table2, despite there being no JOIN.
Perhaps you could explain what it is you are trying to do with this query?

Resources