Checking if an update already took place in ACCESS - sql

I am using the following code, to combine several tables into 1 single Table called DB_Total:
INSERT INTO DB_Total
SELECT *
FROM Tags_DI_DB;
But, if I (accidentally) execute this query twice or three times, the data just gets stacked. Is there a possibility to check wether or not a table is added in the new "mastertable", DB_Total?

INSERT INTO DB_TOTAL
SELECT a.*
FROM Tags_DI_DB a
LEFT JOIN DB_TOTAL b
ON a.colName = b.colName
WHERE b.colName IS NULL
where colName is the unique column

Related

T-SQL Match records 1 to 1 without join condition

I have a group of enitities which need to have another record associated with them from another table.
When I try to output an Id for the table to be matched on it doesn't work because you can only output from inserted, updated etc.
DECLARE #SignatureGlobalIdsTbl table (ID int,
CompanyBankAccountId int);
INSERT INTO GlobalIds (TypeId)
-- I Cannot output cba.Id into the table since its not from inserted
OUTPUT Inserted.Id,
cba.Id
INTO #SignatureGlobalIdsTbl (ID,
CompanyBankAccountId)
SELECT (#DocumentsGlobalTypeKey)
FROM CompanyBankAccounts cba
INNER JOIN Companies c ON c.CompanyId = cba.CompanyId
WHERE SignatureDocumentId IS NULL
AND (SignatureFile IS NOT NULL
AND SignatureFile != '');
INSERT INTO Documents (DocumentPath,
DocumentType,
DocumentIsExternal,
OwnerGlobalId,
OwnerGlobalTypeID,
DocumentName,
Extension,
GlobalId)
SELECT SignatureFile,
#SignatureDocumentTypeKey,
1,
CompanyGlobalId,
#OwnerGlobalTypeKey,
[dbo].[fnGetFileNameWithoutExtension](SignatureFile),
[dbo].[fnGetFileExtension](SignatureFile),
documentGlobalId
FROM (SELECT c.GlobalId AS CompanyGlobalId,
cba.*,
s.ID AS documentGlobalId
FROM CompanyBankAccounts cba
INNER JOIN Companies c ON c.CompanyId = cba.CompanyId
CROSS JOIN #SignatureGlobalIdsTbl s) info
WHERE SignatureDocumentId IS NULL
AND (SignatureFile IS NOT NULL
AND SignatureFile != '');
I Tried to use cross join to prevent cartesian production but that did not work. I also tried to output the rownumber over some value but I could not get that to be stored in the table either.
If I have two seperate queries which return the same amount of records, how can I pair the records together without creating cartesian production?
'When I try to output an Id for the table ... it doesn't work.'
This seems to be because one of the columns you want to OUTPUT is not actually part of the insert. It's an annoying problem and I wish SQL Server would allow us to do it.
Someone may have a much better answer for this than I do, but the way I usually approach this is
Create a temporary table/etc of the data I want to insert, with a column for ID (starts blank)
Do an insert of the correct amount of rows, and get the IDs out into another temporary table,
Assign the IDs as appropriate within the original temporary table
Go back and update the inserted rows with any additional data needed (though that's probably not needed here given you're just inserting a constant)
What this does is to flag/get the IDs ready for you to use, then you allocate them to your data as needed, then fill in the table with the data. It's relatively simple although it does do 2 table hits rather than 1.
Also consider doing it all within a transaction to keep the data consistent (though also probably not needed here).
How can I pair the records together?
A cross join unfortunately multiplies the rows (number of rows on left times the number of rows on the right). It is useful in some instances, but possibly not here.
I suggest when you do your inserts above, you get an identifier (e.g., companyID) in your temp table and join on that.
If you don't have a matching record and just want to assign them in order, you can use an answer similar to my answer in another recent question How to update multiple rows in a temp table with multiple values from another table using only one ID common between them?
Further notes
I suggest avoiding table variables (e.g., DECLARE #yourtable TABLE) and use temporary tables (CREATE TABLE #yourtable) instead - for performance reasons. If it's only a small amount of rows it's OK, but it gets worse as it gets larger as SQL Server assumed that table variables only have 1 row
In your bottom statement, why is there the SELECT statement in the FROM clause? Couldn't you just get rid of that select statement and have the FROM clause list the tables you want?
I figured out a way to have access to the output, by using a merge statement.
DECLARE #LogoGlobalIdsTbl TABLE (ID INT, companyBankAccountID INT)
MERGE GlobalIds
USING
(
SELECT (cba.CompanyBankAccountId)
FROM CompanyBankAccounts cba
INNER JOIN Companies c on c.CompanyId = cba.CompanyId
WHERE cba.LogoDocumentId IS NULL AND (cba.LogoFile IS NOT NUll AND cba.LogoFile != '')
) src ON (1=0)
WHEN NOT MATCHED
THEN INSERT ( TypeId )
VALUES (#DocumentsGlobalTypeKey)
OUTPUT [INSERTED].[Id], src.CompanyBankAccountId
INTO #LogoGlobalIdsTbl;

SQL Inner Join w/ Unique Vals

Questions similar to this one about using DISTINCT values in an INNER JOIN have been asked a few times, but I don't see my (simple) use case.
Problem Description:
I have two tables Table A and Table B. They can be joined via a variable ID. Each ID may appear on multiple rows in both Table A and Table B.
I would like to INNER JOIN Table A and Table B on the distinct values of ID which appear in Table B and select all rows of Table A with a Table A.ID which appears matching some condition in Table B.
What I want:
I want to make sure I get only one copy of each row of Table A with a Table A.ID matching a Table B.ID which satisfies [some condition].
What I would like to do:
SELECT * FROM TABLE A
INNER JOIN (
SELECT DISTINCT ID FROM TABLE B WHERE [some condition]
) ON TABLE A.ID=TABLE B.ID
Additionally:
As a further (really dumb) constraint, I can't say anything about the SQL standard in use, since I'm executing the SQL query through Stata's odbc load command on a database I have no information about beyond the variable names and the fact that "it does accept SQL queries," ( <- this is the extent of the information I have).
If you want all rows in a that match an id in b, then use exists:
select a.*
from a
where exists (select 1 from b where b.id = a.id);
Trying to use join just complicates matters, because it both filters and generates duplicates.

SQL Server : joining 2 tables where each row has unique PKEY value

I am attempting to join 2 tables with an equivalent amount of columns and where each column is named the same. Tb1 is an MS Access table that I have imported to SQL Server. Tb2 is a table that is updated from tb1 quarterly and is used to generate reports.
I have gone into design view and ensured that all column datatypes are the same and have the same names. Likewise, every row in each table is assigned a unique integer value in a column named PKEY.
What I would like to do is add all new entries present in tb1 (the MS Access table) to the existing tb2. I believe this can be done by writing a query that loads all unique pkeys found in tb1 (AKA load all keys that are NOT found in both tables, only load unique keys belonging to rows in the access table) and then appending these entries into Tb2.
Not really sure where to start when writing this query, I tried something like:
SELECT *
FROM tb1
WHERE PKEY <> Tb2.PKEY
Any help would be greatly appreciated. Thanks!
I would recommend not exists:
select tb1.*
from tb1
where not exists (select 1 from tb2 where tb2.pkey = tb1.pkey);
You can put an insert before this to insert the rows into the second table.
Insert into tb2 Select * from tb1 Where tb1.id not in (select Id from tb2)
The script above inserts records to tb2 from the results the first select query.
The select query only returns records with an ID that is not listed in the select sub query.

SQL - Insert Into Select query with lookup of value from another table

Morning all, I need some help please.
I have a database with several tables. I'm trying to write an INSERT INTO and SELECT query that copies all values from one Table (TableA) into another Table (TableD) but substitutes one value with a value it looks up in another table (Table B).
Table A with various fields including TableBRef
Table B includes various fields starting with TableBRef and also includes a field TableCRef
I want to copy all of TableA into Table D but replace The TableBRef with the TableCRef ie I know TableBRef, I need to search for it in TableB and return the associated value from the TableCRef field.
INSERT INTO TableD
(DRef, CRef, DData1, DData2)
SELECT TableA.ARef, TableB.CRef, TableA.AData1, TableA.AData2
FROM TableD AS TableD_1 CROSS JOIN
TableC CROSS JOIN
TableA INNER JOIN
TableB ON TableA.BRef = TableB.BRef
Sorry, I thought that calling them generic table names may help but it's actually a little confusing :-)
I don't understand how you relate each table but see if this query will work for you
INSERT INTO TableD
(DRef, CRef, DData1, DData2)
SELECT a.ARef, c.CRef, a.AData1, a.AData2
from tableA a
left outer join tableB b on a.ARef = b.ARef
inner join tableC c on b.CRef = c.CRef

How to copy lookup_id from Table1 to Table2 with INSERT INTO SELECT

I am a student learning SQL Server and using the management studio to normalize a db which started as a single table.
I now have Table1 with 80,000 rows containing ID, CategoryDescription, etc... with many repeated CateogoryDescriptions.
Table2 has a list of all of the CategoryDescriptions and a DescriptionID column which was created using SELECT DISTINCT. It has about 100 rows.
I want to copy the DescriptionID values from Table2 into Table 1 so that I can delete the large CategoryDescription column and replace it with a link to the lookup table.
The following generates the expected data (a single column of 80,000 ids):
SELECT TEST.dbo.LU_ConNames.Con_ID
FROM TEST.dbo.LU_ConNames
JOIN TEST.dbo.MainTable
ON TEST.dbo.MainTable.CONCESSION = TEST.dbo.LU_ConNames.Con_Name
However, when I add the INSERT INTO...
INSERT INTO TEST.dbo.MainTable
SELECT TEST.dbo.LU_ConNames.Con_ID
FROM TEST.dbo.LU_ConNames
JOIN TEST.dbo.MainTable
ON TEST.dbo.MainTable.CONCESSION = TEST.dbo.LU_ConNames.Con_Name
I get "Column name or number of supplied values does not match table definition." To clarify, there is no column in MainTable called Con_ID. I thought that perhaps that was the problem, but when I added one (and verified the same data type) I get the same error.
You should not be inserting new records as you want to update existing ones.
You can do:
UPDATE TEST.dbo.MainTable
SET TEST.dbo.MainTable.Con_ID = C.Con_ID
FROM TEST.dbo.MainTable T
INNER JOIN TEST.dbo.LU_ConNames C
ON T.CONCESSION = C.Con_Name
Some reading on that topicon MSDN - UPDATE syntax