Insert into statement - sql

I have a table
Moon PIS
pID pAddr cID cName leaseExp mRent oID oName oContact
pID – property id: coded to identify the specific property, chosen to be primary key.
pAddr – property address, required (ie, cannot be null)
cID – client id: coded to identify the client – null means not rented out yet
cName – client name – null means not rented out yet
leaseExp – lease Expiration date – null allowed, if not rented out yet.
mRent – monthly rent (in dollars) – null allowed.
oID – owner id: coded to identify the property owner, required (ie, cannot be null)
oName – owner name, required (ie, cannot be null)
oContact – owner’s contact address.
and I am suppose to normalize this table
I created a table for the property, owner, and client.
The property table has pID, pAddr
the client table has cID, cName the owner table has oID, oName, oContact
first, I was wondering if normalized the table properly?
if so I am then required to move the data from the MoonPIS table into the newly created tables. I have attempted:
INSERT INTO Property (PropertyID, PropertyAddr)
SELECT pID, pAddr FROM Moon PIS
I am receiving an error saying "Microsoft Access database engine could not find the input table or query 'Moon'. Make sure it exist and that its name is spelled correctly."
Do I have to set up relationships prior to transferring the data. All I have done is created the tables and columns.

You need to escape the name because it contains a space:
INSERT INTO Property (PropertyID, PropertyAddr)
SELECT pID, pAddr
FROM [Moon PIS];

This answer isn't valid for the question, as it refers to the original table, and not to the changes suggested in the question... but I'll leave it for now as I think it might be useful anyway, if someone disagrees I'll remove it.
first, I was wondering if normalized the table properly?
No, it's not properly normalized as it records data for multiple types of entites (properties, clients and owners). You'll want to move the client details (cName) and the owner details (oName and oContact) to their own tables (Client and Owner maybe) and just keep the cId and oID as foreign keys.
Also, what is this table supposed to record, right now you include a lot of data that doesn't depend on the primary key (propertyId). Take rent for example, is the rent bound to a property or is it something that relates to a specific contract with a client and can change depending on client? If so, it doesn't belong in the property table. And so on...
Normalizing relational designs can be hard (and involve formal logic), but if you want your design to work, it's a subject well worth putting some time into studying.
As for the query error, don't use white spaces in table names :)

Related

Access Customer Attributes from Generic Inquiry

I need to leverage Customer Attributes in a Generic Inquiry. I devise most of my Generic Inquiries starting with raw SQL in Server Management Studio. I find it much easier to locate the data I need this way. However, I am having a terrible time figuring out how Attributes are tied to Customers. Attributes are added to a Customer Class, and then a customer is associated with a Customer Class. This allows any attributes available for that Customer Class to be modifiable for the Customer.
Using the database, I have found the following:
Individual Attribute objects are stored in the CSAttribute table
Options for the Attributes (such as combobox) are stored in the CSAttributeDetail table
Individual instances of each attribute are stored in the CSAnswers table
There is also a CSAttributeGroup table, which I believe relates CSAttributeDetail records to CSAttribute records.
So, one would expect the CSAnswers table to have a reference to the customer the answer is attached to... but it does not. This table is defined as:
CompanyID (PK, int, not null)
RefNoteID (PK, uniqueidentifier, not null)
AttributeID (PK, nvarchar(10), not null)
Value (nvarchar(255), null)
To add insult to injury, table names in the database do not always align 1-to-1 to what is available in a Generic Inquiry. For example, many fields that are available to ARInvoice in a GI are actually stored in the ARRegister table in the database. I suspect something very similar is going on for Attributes.
Can anyone point me in the right direction of locating how Attributes are associated to Customers at both the database level, and at the GI level?
Attributes are linked to the record with the RefNoteID field; it will match the NoteID of the other record (note that in your case it wouldn't be in the Customers table but in BAccount, which is a 1:1 join with Customers). You should rarely, if ever, need to directly reference the CSAnswers table. Internally, Acumatica will generate a set of virtual fields in the primary table that match the name of the attribute, suffixed with _Attributes:
Please note that you won't be able to reference the attribute in the "Conditions" tab, however you can filter by this column in the grid and create predefined filters.
I've made a number of GIs using Customer Attributes, the RefNoteID uniqueidentifier in the CSAnswers table relates to the NoteID uniqueidentifier on the Customer table, and the AttributeID is the specific Attribute. To get All attributes for a customer on multiple Rows join on just the RefNoteID, if you want specific attribute(s) add additional join conditions for each AttributeID.

How do I create a table model in SQL?

Let's say I've 3 tables: enterprise, users, houses.
Everyone needs an address. What should I do?
Create a table address for everyone?
Create one unique table address?
Assuming that the first is "more" correct (cache, fragmentation, size, ...), how should I write it in plain SQL?
How do I create a "model" of the table address, and use it in custom tables (e.g. enterprise_address)?
* So when I change one field in the model, it gets replicated.
It appears you need every user to have an address. You have multiple ways to solve it.
Handle it in UI
Your users table will be just information about users (on address info here)
Create addresses table with addressid as primary key
Create many-to-many table/junction table called user_addresses that brings userid and addressid together
Ensure that your UI mandates address for each user
Tables
create table addresses (addressid int not null PK, line1, line2, city ...);
create table users (userid int not null PK, username, ...);
create table user_addresses (user_addressid int, userid int, addressid int, UK userid + addressid, FK to users, FK to addresses);
This allows a user to have multiple addresses. You have the flexibility of marking which one is primary.
Handle it in DB (and UI)
create table addresses (addressid int not null PK, ....);
create table users (userid int not null PK, username varchar(20), ..., addressid int not null, FK to addresses);
This allows one address per user.
and handle it also on the UI to ensure that address is supplied. Enter address into addresses first and then into users (make it an atomic process; use transactions!)
You can start with one these methods and analyze what your business needs are. Work with your DBA, if you have one, to see what their experience says about the business and previous DB designs similar to this.
Just from the three given tables I would assume that address is something you would want to put in either Houses or Users.
Depending on how much detail you want to keep track of in the Address it could be work making a separate table but there are a number of ways to go about this and the correct method depends solely on what you are trying to achieve.
Without knowing any of the required information all I can really advise is that you should aim to store the addresses as unique values. Once you have this you can assign each address to any other table you wish using a Foreign Key.
If you want to store multiple fields for the address then you will require a seperate table, if a single field will do then it could just as easily be added to the person or houses table.
One thing that would make a major difference to which way you would want to do this is the relationship between address and your other entities. For example if a user can have many addresses then you cant make it a part of the user table, and if an address can have multiple users assigned to it then it cant use a FK to represent its relationship to the users table.
One way you can do this is to make a relational table. So you make addresses and users seperate tables then have another table with just an id(pk) and 2 fks linking it to each of the other tables. This way you can have a many to many relationship if you wish.
First question: how many addresses per enterprise/user/house? If there are multiple addresses per entity, that leads you to want a separate address table, possibly with an address type.
Examples of multiple address situations:
Multiple locations
Ship-to addresses
Physical vs. PO Box
If you are going to assert that an entity can only have one address, then you probably prefer making the address part of the entity row, for simplicity. However, there can be reasons not to do that; for example, table width (number of columns in the table).
If you have multiple addresses per entity, typically you will use a foreign key. The entity should have an abstract key: some kind of ID. This will either be an integer or, in SQL Server, it could be a uniqueidentifier. The entity ID will be part of the key for the address.
Ok, I found the answer to postgresql: use INHERITS
e.g. CREATE TABLE name () INHERITS (table_model)
Thank you all for the answers.

Db design - table dependency and naming conventions

I'm about to design a db for a new project and I'm kinda stuck on some "concept" stuff.
My initial question is very similar to this one.
Relational table naming convention
That is:
"If I got a table "user" and then I got products that only the user
will have, should the table be named "user-product" or just "product"?
This is a one to many relationship."
In the above thread I found the answer by PerformanceDBA very useful and well written,
but I'm not sure about some points. Quoting part of the answer:
"It doesn't matter if user::product is 1::n. What matters is whether product is a separate entity and whether it is Independent, ie. it can exist on its own. Therefore product, not user_product. And if product exists only in the context of an user, ie. it is Dependent,
then user_product."
This is a very interesting point, but generates another question:
what exactly are the definitions of Independent and Dependent table?
Example 1, we have two tables:
The table User
Id
Username
FullName
The 1::n table Message, representing a collection of messages sent by the users
UserId (FK to User.Id)
Text
The Message table is dependent from the User table or not?
The question I'm asking to myself here, is: "Would the message entity exist without the user?" but I'm not sure about the answer, because it would be "the message would exist but would be anonymous." is this enough to make the Message table dependent from the User table (so i should name the table "UserMessage")?
Example 2, we have two tables:
The table User
Id
Username
FullName
The 1::1 table Profile, representing a user profile
UserId (FK to User.Id)
First Name
Last Name
Gender
Same question, is the table Profile dependent by the User table? I think it is, because a profile without a user would not really make sense.
I'm not sure though, so how can I decide safely if a table is dependent by another or not?
I think you may really have 3 entities to consider. User, product and user_product. Test relationships by describing them with a verb. The relationship between a user and a product is most likely a many-to-many (a user can order many products, and a product can be ordered by many users). This indicates that a composite table between them that takes the primary keys of both tables is needed (and maybe attributes only if they describe a fact about the user/product combination). user_product is what links a user with his products (and a product with who ordered it) and is thus dependent.
That said, in your examples the message and profile tables are dependent, since they cannot exist without a user (their primary key). Use user - user_message and user - user_profile.
Another example of an independent table would be a lookup table (code/description table).
To answer your last question, an entity is considered dependent if its primary key must exist in another entity before it can exist i.e you can't have a profile without a user so it is dependent.

Key Manager Database Design

My task is to add some functionality to an existing web application using SQL Server.
My client's business provides a service where keys are issued to employees who then go to the various locations to perform the requested work. She wants to keep track of who has what keys for their clients. They have about 100-125 clients and 6 employees. She will be the only person using the web gui for the issuance and returning of keys.
For inspiration, I went to Google and found a demo program called KEY ORGANIZER which runs on the desktop. It does exactly what my client is looking for but is a desktop app, not a web app. So, I figured I’d just reverse engineer it and tailor it for my client’s needs. The desktop application does way more than my client needs. Here is a high level overview of what she is looking for:
Issuing of Keys:
She clicks on the key image next her customer’s name. Let’s say she has 3 keys for the customer but all 3 are already checked out to employees. She would receive an alert of some kind stating there are no keys available to issue but would still allow her to issue a key in situations were inventory is off (so the database needs to be able to handle negative values). If there is a key available, then proceed to the next bullet.
In the next window, she is presented with a form. (list of employees name to choose from and today's date).
She selects the employee from the drop down list and clicks the OK button and the modal window closes.
A log entry is entered for every check-out/check-in and an email will be sent to the employee upon each check-in and check-out.
Returning of Keys:
She would also like to be able to select a button next to an client’s name to see which employees currently has a key and be able to select an employee’s name to return a key.
Similarly, my client would like to click on the employee’s name to see if a list of keys in their possession and be able to return a key from the list, too.
A log entry is entered for every check-out/check-in and an email will be sent to the employee upon each check-in and check-out.
I do not need help with the coding of the web page. I just need some guidance on how to properly setup the database tables (e.g. should the key inventory field be a part of an existing table or a different table for example) to best handle the revolving key inventory scenario.
Here are the tables I’ve come up with:
Customer_tbl (existing table)
• CustomerID
• KeyQTY (new field?)
• KeyLabel (new field?)
Employee_tbl (existing table)
• EmployeeID
• Fn
• Ln
KeyJournal_tbl (new table)
• JournalID
• ActionDate
• ActionPerformedID (key issue, key returned, key lost, etc)
• CustomerID
• EmployeeID
• Inventory (the total number of keys received from the customer – or should this be under Customer_tbl?)
• IssueReturnDate
KeyInventory_tbl (new table)
• KeyID
• CustomerID
• KeyTotal
NOTE: I added the SQL Server 2005 tag only for reference. I don't need help with the SQL statements in case that tag is misleading.
My inclination would be something pretty close to yours. Here:
Customer
customer_id
name, address, etc, whatever reference info you need
Employee
employee_id
name, etc
KeyInventory
key_id
description
customer_id
qty
KeyCheckout
employee_id
key_id
checkout_date
return_date
Notes:
I put a description on KeyInventory because I'm assuming you could have more than one key for a customer and you need to distinguish them, like "Apt 1" and "Apt 2", or "Warehouse" and "Office".
When an employee is given a key, create a KeyCheckout record with the date it was given. When the key is returned, fill in the return date. If the return date is null the key is still out.
To find which employees have keys for customer #cx:
select employee_id
from KeyCheckout c
join KeyInventory i on i.key_id = c.key_id
where i.customer_id = #cx
and c.return_date is null
To find how many of key #kx are still available:
select i.qty - count(c.employee_id)
from KeyInventory i
join KeyCheckout c on c.key_id=i.key_id and c.return_date is not null
where i.key_id = #kx
Etc.
You'd definitely want an index on return_date, or maybe KeyCheckout(key_id,return_date) and KeyCheckout(employee_id,return_date), because this table will grow quite large and without an index queries will get unbearably slow.
I think your Journal table is a similar concept to my Checkout. I'm just putting the checkout and return fields in one record to make it easier to determine if a key is still out. With separate records for in and out, you have to match them up, which is a pain.
Don't put the qty into a journal-type record. That's not an attribute of the "transaction", it's an attribute of the key itself. It belongs in the inventory table.
Don't put the key qty in the customer record. If you need to know how many different keys a customer has, just do select count(*) from keyinventory where customer_id=#cx. Storing this count in the customer record just creates the possibility that it won't match the actual number of key records.
I'm not sure what "keylabel" is. If that's a description of the key, it belongs in the KeyInventory record, because a customer could have more than one key. I don't think it makes sense to say that a customer can have only one key. Even if that happens to be true of your customers today, it seems likely that a customer could have multiple keys in the future, might as well allow for it.
I think your inventory is non-serialized, i.e. 3 keys for the same lock are not distinguished from each other, it's just "quantity 3", right? If they have individual serial numbers on them or something, then there would be no quantity field and you'd have individual records for each key.

Design Pattern required for database schema with two classes both composing a third class

Consider a system which has classes for both letters and people; both of these classes compose an address. When designing a database for the system it seems sensible to have a separate schema for the address but this leads to an issue; I don't know how to have a foreign key in the address table cleanly identify what it belongs to because the foreign key could identify either a letter or a person. Further more I expect that further classes will be added which will also compose an address.
I would be grateful for design patterns addressing this kind of design point.
Best Regards
I don't know how to have a foreign key
in the address table cleanly identify
what it belongs to because the foreign
key could identify either a letter or
a person.
It sounds like you have got that the wrong way around. There would be no foreign key in the address table; rather, the letters table would have a foreign key referencing the address table and the persons table would also have a foreign key referencing the address table.
In SQL, the REFERENTIAL_CONSTRAINTS view in the Information Schema catalog will tell you which tables are referencing the address table.
In our shop we regularly debate whether an address should be modelled as an entity in its own right. The problem with treating an address as an entity is that there is no reliable key beyond the attributes themselves (postal code, house name or number, etc) and many variations can identify the same address (I can write my home address twenty different ways). Then you need to consider post office boxes, care of addresses, Santa Claus, etc. And the Big Question: do you allow an address to be amended? If someone moves house, do they keep the same address entity with amended attributes (that way all linked entities get the address change) or do you lock-down addresses' attributes and force the creation of a new address entity then relink all the referencing addresses to the new one (and do you delete the now-orphaned address entity and if yes then why did you bother to replace it...?) But your application still needs to allow an address to be amended in case the post office changes it in real life, but how to you prevent this ability from being misused i.e. using it for aforementioned illegal house moves? You can use a webservice to scrub your address data so that is is correct but an external system way have less clean data and therefore you can't get your address entities to match anymore...?
I like to keep it simple: an address is a single attribute being the plaintext you must put on an item of mail for it to be delivered by the post office to the addressable entity in question; it is not an entity in its own right because it lacks an identifier. For practical reasons (e.g. being able to print it on an address label), this single attibute is usually split into subatomic elements (address_line_1, address_line_2, ... postal_code, whatever).
Because most SQL products lack support for domains, I have no problem duplicating the column names, data types, constraints, etc between for each table that models an addressable entity.
Surely the foreign keys should be from the Letter and People tables referencing the primary key on the Address table?
So, the Letter table contains an AddressId column referencing the Id on the Address table, as does the Person table, and any future classes which compose an address.
If Letters and Persons compose multiple addresses, then intermediate link tables will be required.