How to make multiple select into on the same table? - sql

Hi i got a little problem right now i'm doing Stored Proc in sql server. I wanna get some result from multiple table and put it into a temporary table. So I thought i could use a "Select into" statement wich work fine until i decided to add multiple select into the temporary table. For example: Here's my code:
while #Compteur <= #wrhCodeEnd
select lp.lotQty ,lp.lotID into ZeTable from TB_lotLot ltlt
inner join TB_lotPal lp on ltlt.lotID=lp.lotID
inner join TB_palSuper ps ON lp.spID=ps.spID
inner join TB_expExpeditionLot eel ON eel.lotID=lp.spID
where ps.wrhID <> #Compteur and
ltlt.wrhID = #Compteur and
lp.lotID not in(select ZeTable.lotID from ZeTable)
the thing is I don't know if I can make multiple select into on the same temporary table and I also wanna check with a where clause the information in the table is not already there.
Thx in Advance

You can create temporary table and can use insert statement to add records with required columns and can drop it after use.

Related

Best way to "SELECT *" from multiple tabs in sql without duplicate?

I am trying to retrieve every data stored in 2 tabs from my database through a SELECT statement.
The problem is there are a lot of columns in each tab and manually selecting each column would be a pain in the ass.
So naturally I thought about using a join :
select * from equipment
join data
on equipment.id = data.equipmentId
The problem is I am getting the equipment ID 2 times in the result.
I thought that maybe some specific join could help me filter out the duplicate key, but I can't manage to find a way...
Is there any way to filter out the foreign key or is there a better way to do the whole thing (I would rather not have to post process the data to manually remove those duplicate columns)?
You can use USING clause.
"The USING clause specifies which columns to test for equality when
two tables are joined. It can be used instead of an ON clause in the
JOIN operations that have an explicit join clause."
select *
from test
join test2 using(id)
Here is a demo
You can also use NATURAL JOIN
select *
from test
natural join test2;

Insert Into where not exists from specific category

I have a table that contains several repair categories, and items that are associated with each repair category. I am trying to insert all the standard items from a specific repair category that don't already exist into a Details table.
TblEstimateDetails is a join table for an Estimate Table and StandardItem Table. And TblCategoryItems is a join table for the Repair Categories and their respective Standard Items.
For example in the attached image, Left side are all the Standard Items in a Repair Category, and Right side are all the Standard Items that are already in the EstimateDetails table.
Standard Items All vs Already Included
I need to be able to insert the 6 missing GUIDS from the left, and into the table on the right, and only for a specific estimate GID.
This is being used in an Access VBA script, which I will translate into the appropriate code once I get the sql syntax correct.
Thank you!
INSERT INTO TblEstimateDetails(estimate_GID, standard_item_GID)
SELECT
'55DEEE29-7B79-4830-909C-E59E831F4297' AS estimate_GID
, standard_item_GID
FROM TblCategoryItems
WHERE repair_category_GID = '32A8AE6D-A512-4868-8E1A-EF0357AB100E'
AND NOT EXISTS
(SELECT standard_item_GID
FROM TblEstimateDetails
WHERE estimate_GID = '55DEEE29-7B79-4830-909C-E59E831F4297');
Some things to try: 1) simplify to a select query to see if it selects the right records, 2) use a NOT IN statement instead of NOT EXISTS. There's no reason NOT EXISTS shouldn't work, I'd just try a different way if it isn't working.
SELECT '55DEEE29-7B79-4830-909C-E59E831F4297' AS estimate_GID,
standard_item_GID
FROM TblCategoryItems
WHERE repair_category_GID = '32A8AE6D-A512-4868-8E1A-EF0357AB100E'
AND standard_item_GID NOT IN
(SELECT standard_item_GID FROM TblEstimateDetails
WHERE estimate_GID = '55DEEE29-7B79-4830-909C-E59E831F4297');
Got it figured out. Access needs the subquery to be correlated to main query to work. So I set the WHERE clause in the subquery to equal the matching column in the main query. And I had to join the Estimates table so that it picked only the items in a specific estimate.
SELECT
'06A2E0A9-9AE5-4073-A856-1CCE6D9C48BB' AS estimate_GID
, CI.standard_item_GID
FROM TblCategoryItems CI
INNER JOIN TblEstimates E ON CI.repair_category_GID=E.repair_category_GID
WHERE E.repair_category_GID = '15238097-305E-4456-B86F-3787C9B8219B'
AND NOT EXISTS
(SELECT ED.standard_item_GID
FROM TblEstimateDetails ED
WHERE E.estimate_GID=ED.estimate_GID
);

Cannot update a table using a simple inner join

I have 2 tables in access 2007.
See attached picture to see the structure of the tables and the expected result.
I am trying to update the quantity field (ITQTY) in TABLE_BLNC by summarizing all the quantity field (LOCQTY) from TABLE_DTL for same items (LOITNBR=ITNBR).
In TABLE_BLNC, the item is unique while in TABLE_DTL, the item can be in multiple records.
My query is:
UPDATE TABLE_BLNC INNER JOIN
(
SELECT LOITNBR, Sum(LOCQTY) AS SumOfLOCQTY FROM TABLE_DTL GROUP BY LOITNBR) AS DTL
ON TABLE_BLNC.ITNBR=DTL.LOITNBR SET TABLE_BLNC.ITQTY = DTL.SumOfLOCQTY;
I am getting the error:
Operation must use an updateable query.
Domain Aggregate functions can be useful when Access complains that an UPDATE is not updateable. In this case, use DSum() ...
UPDATE TABLE_BLNC
SET ITQTY =
DSum("LOCQTY", "TABLE_DTL", "LOITNBR='" & ITNBR & "'");
Index TABLE_DTL.LOITNBR for optimum performance.
One of the great annoyances of Access SQL is its inability to update a table from an non-updatable source. Non-updatable sources include read-only links to ODBC tables, and GROUP BY (summary) queries.
What I always do is:
Copy the structure of TABLE_BLNK to a temp table: TABLE_BLNK_temp.
In your code, first delete the temp:
DELETE * FROM TABLE_BLNK_temp;
Insert the result of your summary query into temp:
INSERT INTO TABLE_BLNK_temp (ITNBR, ITQTY)
SELECT LOITNBR, Sum(LOCQTY) AS SumOfLOCQTY
FROM TABLE_DTL GROUP BY LOITNBR;
Update TABLE_BLNK from TABLE_BLNK_temp:
UPDATE TABLE_BLNC INNER JOIN TABLE_BLNK_temp AS t
ON TABLE_BLNC.ITNBR = t.ITNBR
SET TABLE_BLNC.ITQTY = t.ITQTY;
While it is an extra step or two, this approach:
Always works
Is more performant than Domain Aggregate functions for larger datasets

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.

Avoiding join in MS Access delete query

I am trying to create a delete query to remove records from one table, based on whether or not one of the field exists in another master table. The situation is that I am importing new records into a database, but I want to remove the records that have already been imported, i.e. that already have an account in the master table. The field I need to join on, however is not equal: it is prefixed with a constant three letter code XYZ.
tbl_to_import.Account master_table.Account
123456 XYZ.123456
345678 XYZ.345678
To avoid using a join in the delete query I tried the following:
Delete tbl_to_import.*
From tbl_to_import
Where Exists( Select master_table.Account From master_table
Where master_table.Account = ("XYZ."& tbl_to_import.Account) ) = True;
However, the query gets hung up in Access. I'm not sure what I'm doing incorrectly. I don't get an error message, but the query runs without producing anything and I eventually stop it. In this situation, tbl_to_import has 2,700 records and master_table has 50,000 records. Additionally, I am connecting to the master_table via ODBC.
Originally, I constructed two queries using a join to perform the delete. tbl_to_import.Account has a primary key called ID. One query, qry_find_existing_accounts, located the ID numbers in tbl_to_import for which there exists a corresponding account in master_table.Account:
SELECT DISTINCTROW tbl_to_import.ID AS DELETEID
FROM tbl_to_import LEFT JOIN master_table
ON ("XYZ."& tbl_to_import.Account) = master_table.Account
WHERE ((("XYZ." & [Account])=[master_table].[Account]));
Then I used this query to construct the delete query:
DELETE DISTINCTROW tbl_to_import.*, tbl_to_import.ID
FROM tbl_to_import RIGHT JOIN qry_find_existing_accounts
ON tbl_to_import.ID =qry_find_existing_accounts.DELETEID
WHERE (((tbl_to_import.ID)=[qry_find_existing_accounts].[DELETEID]));
The query qry_find_existing_accounts worked fine; however, when I tried to run the second query to delete, I got the error: Could not delete from specified tables. Typically, when I get this error, it is because I have not selected unique records only, however, I used DISTINCTROW in both queries.
Any ideas what I am doing wrong and how I can accomplish what I need to do?
I'd go with a simpler nested SQL statement:
Delete tbl_to_import.*
From tbl_to_import
Where "XYZ." & tbl_to_import.Account In
(Select master_table.Account From master_table);
This should be fairly fast, especially if your Account fields are indexed.
I think you can simplify the query; delete based on the ID, where the IDs are in the query:
DELETE * FROM tbl_to_import
WHERE tbl_to_import.ID IN (
SELECT DISTINCT [DELETED] FROM qry_find_existing_accounts
)