SQL: I need to take two fields I get as a result of a SELECT COUNT statement and populate a temp table with them - sql

So I have a table which has a bunch of information and a bunch of records. But there will be one field in particular I care about, in this case #BegAttField# where only a subset of records have it populated. Many of them have the same value as one another as well.
What I need to do is get a count (minus 1) of all duplicates, then populate the first record in the bunch with that count value in a new field. I have another field I call BegProd that will match #BegAttField# for each "first" record.
I'm just stuck as to how to make this happen. I may have been on the right path, but who knows. The SELECT statement gets me two fields and as many records as their are unique #BegAttField#'s. But once I have them, I haven't been able to work with them.
Here's my whole set of code, trying to use a temporary table and SELECT INTO to try and populate it. (Note: the fields with # around the names are variables for this 3rd party app)
CREATE TABLE #temp (AttCount int, BegProd varchar(255))
SELECT COUNT(d.[#BegAttField#])-1 AS AttCount, d.[#BegAttField#] AS BegProd
INTO [#temp] FROM [Document] d
WHERE d.[#BegAttField#] IS NOT NULL GROUP BY [#BegAttField#]
UPDATE [Document] d SET d.[#NumAttach#] =
SELECT t.[AttCount] FROM [#temp] t INNER JOIN [Document] d1
WHERE t.[BegProd] = d1.[#BegAttField#]
DROP TABLE #temp
Unfortunately I'm running this script through a 3rd party database application that uses SQL as its back-end. So the errors I get are simply: "There is already an object named '#temp' in the database. Incorrect syntax near the keyword 'WHERE'. "

Comment out the CREATE TABLE statement. The SELECT INTO creates that #temp table.

Related

JOIN of DB table and internal table produces "is not defined in the ABAP Dictionary"

First: I'm working on a existing code and want to add some new stuff to it and I'm really new to ABAP
My goal: I want to duplicate an existing table and remove all values that occur multiple times. That - at least I think - works. Afterwards I want to INNER JOIN this new created table with another already existing table, but unfortunately I always get the following error:
Method MethodName "newCreatedTable" is not defined in the ABAP Dictionary as a table, projection view, or database view
Additional Info: As you can see I'm working inside of a method!
Here is my code what I've done so far:
creating new table and delete all duplicates
DATA newCreatedTable TYPE STANDARD TABLE OF existingTable.
SELECT columnName
FROM existingTable INTO TABLE newCreatedTable.
DELETE ADJACENT DUPLICATES
FROM newCreatedTable COMPARING columnName.
here is where the error happens
SELECT *
FROM anotherExistingTable as p
INNER JOIN newCreatedTable as t on t~columnName = p~columnName
...
I hope someone can help me out in this case! Thank You in advance!
If I'm not wrong your code looks like this:
DATA newCreatedTable TYPE STANDARD TABLE OF existingTable.
SELECT columnName FROM existingTable INTO TABLE newCreatedTable.
DELETE ADJACENT DUPLICATES
FROM newCreatedTable COMPARING columnName.
SELECT *
FROM anotherExistingTable
INNER JOIN newCreatedTable as t on t~columnName = p~columnName
If this is the case then you cannot make a SELECT on an internal table. You can only make this operation on a table that exists in the ABAP dictionary.
Your code should look like this:
DATA newCreatedTable TYPE STANDARD TABLE OF existingTable.
SELECT columnName
FROM existingTable INTO TABLE #newCreatedTable.
DELETE ADJACENT DUPLICATES FROM newCreatedTable COMPARING columnName.
SELECT *
FROM anotherExistingTable
FOR ALL ENTRIES IN #newCreatedTable " <-------------- Use FOR ALL ENTRIES
WHERE columnName = #newCreatedTable-columnName. " <-- in your code

Adding Row in existing table (SQL Server 2005)

I want to add another row in my existing table and I'm a bit hesitant if I'm doing the right thing because it might skew the database. I have my script below and would like to hear your thoughts about it.
I want to add another row for 'Jane' in the table, which will be 'SKATING" in the ACT column.
Table: [Emp_table].[ACT].[LIST_EMP]
My script is:
INSERT INTO [Emp_table].[ACT].[LIST_EMP]
([ENTITY],[TYPE],[EMP_COD],[DATE],[LINE_NO],[ACT],[NAME])
VALUES
('REG','EMP','45233','2016-06-20 00:00:00:00','2','SKATING','JANE')
Will this do the trick?
Your statement looks ok. If the database has a problem with it (for example, due to a foreign key constraint violation), it will reject the statement.
If any of the fields in your table are numeric (and not varchar or char), just remove the quotes around the corresponding field. For example, if emp_cod and line_no are int, insert the following values instead:
('REG','EMP',45233,'2016-06-20 00:00:00:00',2,'SKATING','JANE')
Inserting records into a database has always been the most common reason why I've lost a lot of my hairs on my head!
SQL is great when it comes to SELECT or even UPDATEs but when it comes to INSERTs it's like someone from another planet came into the SQL standards commitee and managed to get their way of doing it implemented into the final SQL standard!
If your table does not have an automatic primary key that automatically gets generated on every insert, then you have to code it yourself to manage avoiding duplicates.
Start by writing a normal SELECT to see if the record(s) you're going to add don't already exist. But as Robert implied, your table may not have a primary key because it looks like a LOG table to me. So insert away!
If it does require to have a unique record everytime, then I strongly suggest you create a primary key for the table, either an auto generated one or a combination of your existing columns.
Assuming the first five combined columns make a unique key, this select will determine if your data you're inserting does not already exist...
SELECT COUNT(*) AS FoundRec FROM [Emp_table].[ACT].[LIST_EMP]
WHERE [ENTITY] = wsEntity AND [TYPE] = wsType AND [EMP_COD] = wsEmpCod AND [DATE] = wsDate AND [LINE_NO] = wsLineno
The wsXXX declarations, you will have to replace them with direct values or have them DECLAREd earlier in your script.
If you ran this alone and recieved a value of 1 or more, then the data exists already in your table, at least those 5 first columns. A true duplicate test will require you to test EVERY column in your table, but it should give you an idea.
In the INSERT, to do it all as one statement, you can do this ...
INSERT INTO [Emp_table].[ACT].[LIST_EMP]
([ENTITY],[TYPE],[EMP_COD],[DATE],[LINE_NO],[ACT],[NAME])
VALUES
('REG','EMP','45233','2016-06-20 00:00:00:00','2','SKATING','JANE')
WHERE (SELECT COUNT(*) AS FoundRec FROM [Emp_table].[ACT].[LIST_EMP]
WHERE [ENTITY] = wsEntity AND [TYPE] = wsType AND
[EMP_COD] = wsEmpCod AND [DATE] = wsDate AND
[LINE_NO] = wsLineno) = 0
Just replace the wsXXX variables with the values you want to insert.
I hope that made sense.

access 2010 append data into table without overwriting existing records

Sorry for the long question/post but need some help as I've been searching for several days but havent found anything that helps. Seems like it should be easy but..here goes
I have table1 in my (Access 2010) database that has exising records. I have another table2 that after I run a query, it first deletes the data in table 2, then imports new records into that table. I run the import into table 2 on a semi regular basis but have yet to copy all those records into table 1 successfully.
I need to copy only the records from table 2 to table 1 if the records don't already exist in table1. So, each time the query or vba code would run, it would be continuing to grow table 1 without duplicating existing data.
To clarify further, it's data from the Outlook GAL so each time table2 imports that data (lname,fname,phone,email) it needs to be added to table1, but only if it doesn't already exist in table 1.
I have a small start of SQL but cannot get it to work properly because I'm not sure how to add the other fields into this SQL statement properly (unfortunately I don't know a whole lot about SQL or creating an append query):
INSERT INTO [Current] ( FirstName )
SELECT DISTINCT tblglobaladdresslistimport.First
FROM tblglobaladdresslistimport LEFT JOIN [Current] ON tblglobaladdresslistimport.First = Current.FirstName
WHERE Current.FirstName Is Null;
How about this :
INSERT INTO [Current](FirstName, LastName, Phone, Email)
SELECT DISTINCT
tblglobaladdresslistimport.First
, tblglobaladdresslistimport.Last
, tblglobaladdresslistimport.Phone
, tblglobaladdresslistimport.Email
FROM
tblglobaladdresslistimport LEFT JOIN [Current]
ON tblglobaladdresslistimport.First = Current.FirstName
AND tblglobaladdresslistimport.Last = Current.LastName
AND tblglobaladdresslistimport.Phone = Current.Phone
AND tblglobaladdresslistimport.Email = Current.Email
WHERE Current.FirstName Is Null
AND Current.LastName Is Null
AND Current.Phone Is Null
AND Current.Email Is Null;
Adjust column names if I guessed it wrong. That assumed that you don't have primary key, so data in tblglobaladdresslistimport considered already exists if there is a row in Current having same value for all columns.

Validate Data in SQL Server Table

I am trying to validate the data present in SQL Server table using a stored procedure.
In one of the validation rules, i have to check whether the value of a particular column is present in another table.
Suppose i have a staging table with following columns Cat_ID, Amount, SRC_CDE
I have a 'maintable' with following columns CatID , Cat_Name
I have to validate whether the Cat_ID present in staging table exists in the 'maintable' for each row
I am using the following statement to validate
if((Select count(*) from maintable where CatID= #Cat_id) >0 )
-- Do something if data present
I want to know if there is any better way of doing the above thing other than using a select query for every row.
Can i use some sort of an array where i can fetch all the CatID from maintable and the check instead of using a select query.
Thanks
Using a left join to list all the invalid rows.
select
staging.*
from
staging
left join maintable
on staging.catid=maintable.catid
where maintable.catid is null

SQL query select from table and group on other column

I'm phrasing the question title poorly as I'm not sure what to call what I'm trying to do but it really should be simple.
I've a link / join table with two ID columns. I want to run a check before saving new rows to the table.
The user can save attributes through a webpage but I need to check that the same combination doesn't exist before saving it. With one record it's easy as obviously you just check if that attributeId is already in the table, if it is don't allow them to save it again.
However, if the user chooses a combination of that attribute and another one then they should be allowed to save it.
Here's an image of what I mean:
So if a user now tried to save an attribute with ID of 1 it will stop them, but I need it to also stop them if they tried ID's of 1, 10 so long as both 1 and 10 had the same productAttributeId.
I'm confusing this in my explanation but I'm hoping the image will clarify what I need to do.
This should be simple so I presume I'm missing something.
If I understand the question properly, you want to prevent the combination of AttributeId and ProductAttributeId from being reused. If that's the case, simply make them a combined primary key, which is by nature UNIQUE.
If that's not feasible, create a stored procedure that runs a query against the join for instances of the AttributeId. If the query returns 0 instances, insert the row.
Here's some light code to present the idea (may need to be modified to work with your database):
SELECT COUNT(1) FROM MyJoinTable WHERE AttributeId = #RequestedID
IF ##ROWCOUNT = 0
BEGIN
INSERT INTO MyJoinTable ...
END
You can control your inserts via a stored procedure. My understanding is that
users can select a combination of Attributes, such as
just 1
1 and 10 together
1,4,5,10 (4 attributes)
These need to enter the table as a single "batch" against a (new?) productAttributeId
So if (1,10) was chosen, this needs to be blocked because 1-2 and 10-2 already exist.
What I suggest
The stored procedure should take the attributes as a single list, e.g. '1,2,3' (comma separated, no spaces, just integers)
You can then use a string splitting UDF or an inline XML trick (as shown below) to break it into rows of a derived table.
Test table
create table attrib (attributeid int, productattributeid int)
insert attrib select 1,1
insert attrib select 1,2
insert attrib select 10,2
Here I use a variable, but you can incorporate as a SP input param
declare #t nvarchar(max) set #t = '1,2,10'
select top(1)
t.productattributeid,
count(t.productattributeid) count_attrib,
count(*) over () count_input
from (select convert(xml,'<a>' + replace(#t,',','</a><a>') + '</a>') x) x
cross apply x.x.nodes('a') n(c)
cross apply (select n.c.value('.','int')) a(attributeid)
left join attrib t on t.attributeid = a.attributeid
group by t.productattributeid
order by countrows desc
Output
productattributeid count_attrib count_input
2 2 3
The 1st column gives you the productattributeid that has the most matches
The 2nd column gives you how many attributes were matched using the same productattributeid
The 3rd column is how many attributes exist in the input
If you compare the last 2 columns and the counts
match - you can use the productattributeid to attach to the product which has all these attributes
don't match - then you need to do an insert to create a new combination