How to default a column value from another table? - sql-server

Imagine I have two tables named Account and AccountStatus. In the Account table I got my account data including the accountStatusID by a Foreign Key referencing AccountStatus Primary Key.
In the AccountStatus table I insert all my possible user status (E.g. Account Non-Activated, Account Activated, Account Banned, etc).
Now my problem is when I insert an Account, I want my default value from AccountStatus to be "Account Non-Activated" which have some ID. I can't figure out how I can make this happen without hardcoding, like an Insert Trigger getting Select ID From AccountStatus WHERE AccountStatusTitle = "Account Non-Activated" and set the field (accountStatusID) from Account table.

The simplest option here would be to hard-code the ID using a default constraint. If however you really want to avoid this then I would recommend the following:
a) Add an 'IsDefault' column to your AccountStatus table
b) Add a default constraint to the AccountStatusId field on the Account Table which calls a function which will return the id of the AccountStatus where the IsDefault column is set to true.
Hope this helps.

Related

Is there is a constraint to make sure one column has and only matched column

I have a problem to set correct constraint to make sure one column has and only has one matched column within the table.
For example, company Apple has Bloomberg ticker AAPL:US and only has this ticker. Otherwise, SQL Server will notice there is a error.
I try to use constraint with unique, but it does not work.
I imagine that your schema might be a standard one using a junction table. That is, your tables might look something like:
company (id, name)
ticker (id, name)
company_ticker (id_company, id_ticker)
That is, the company_ticker table is a junction table which stores the relationships between companies and tickers. Normally, this table would by default be many-to-many. But if you want to restrict a company to having only one ticker, then you may place a unique constraint on the id_company column:
CREATE TABLE company_ticker (
id_company INT NOT NULL,
id_ticker INT NOT NULL,
PRIMARY KEY (id_company, id_ticker),
CONSTRAINT cnstr UNIQUE (id_company)
);
With the above unique constraint in place, your schema will only allow a given company to have one relationship with some ticker.

Prevent non-primary key column to have duplicates

I read in this site that it is recommended use an auto-number ID rather than username for primary keys because it will not change. However, how do I prevent the database to have only unique usernames. I am using Access.
In Access, open the table in Design View and click on the username field. In the "Field Properties" pane at the bottom, select Yes (No Duplicates) for the Indexed property. That will prevent duplicate username values from being entered.
Set unique constraint on username column (some main table for user).
You always can validate before inserting (for prompting user) or on trigger before insert.
I take it you've already made the table, so run this query:
ALTER TABLE users
ADD UNIQUE(username)
Change table name and column name in the query to match your table and column name, obviously.
Here's the reference: http://www.w3schools.com/sql/sql_unique.asp

I want to save my adminhtml form data to multiple tables in database

I have created a form in admin panel with various fields. Now the fields here doesn't belong to one single table. On the save, I want some values go into one particular table while others to go into some other table. I am able to show up the data using joins but don't know how to save them back.
Lets say, I have a tblUser with fields:
tblUser
- user_id INT(11) Auto Increment
- username VARCHAR(15)
- store_id SMALLINT(5)
- bank_id INT(11)
Here, store_id and bank_id have foreign key constraints to auto-increment id's of tblcore_store (id, store_name) and tblBanks (id, bank_name, bank_acc) respectively.
Now the fields in the form are:
Username
Store Id
Store Name
Bank Name
Bank Account
When, admin click save I want the data of form to go into their respective tables and also having their references in store_id and bank_id.
First you have to insert data into tblcore_store and tblbanks then you can find the ids by table status or fetching last record from both of table.
after getting both ids now you can insert data to tblUser
you can follow the below steps in any framework
Start new transaction
Insert data into 1st table
Get last insert id
Insert data into 2nd table using last insert id from point above
Close transaction
Return transaction status or anything you might need from this model function
Don’t forget to use a database that is capable of using transactions, otherwise this does nothing.

A better database design on SQL Server?

In SQL Server, I need to design a User table. It should have a UserID (int), a RoleID (int) and a UserName (nvarchar(255)).
A user can be assigned with a name but possibly multiple roles so a UserId may correspond to multiple RoleIDs. This makes it difficult to assign primary key to UserID as UserID may duplicate.
Is there any better design other than breaking it up into multiple tables?
You should have:
1. a user table with UsertId(int), UserName (Varchar)
2. a role table with RoleId(int), RoleName(Varchar)
3. a user_role table with user_id(int), role_id(int)
And don't forget to add the proper indexing and foreign keys.
Ye, have a table Roles, then RolesUsers with UserID and RoleID, and lastly a Users table
edit: where the UserID + RoleID in the RolesUsers are a composite key

Updating foreign keys in SQLServer like Access

I have a table, Contacts, with a primary key of ContactID, which is an identity column. I have another table, Person, with a primary key of PersonID that is a foreign key to ContactID. When I insert a record into Person, I would like PersonID to pull the corresponding identity from ContactID in Contact.
In Access, I simply make a query that references both tables, and it will fill in the foreign key column with the corresponding value in the identity (autonumber) column.
SELECT Person.PersonID, Person.FirstName, Person.MiddleName, Person.LastName, Contact.ContactID, Contact.EmailAddress, Contact.PhoneNumber
FROM (Contact INNER JOIN Person ON Contact.ContactID = Person.PersonID);
How can we achieve this in SQLServer 2008 R2? I have been programming triggers to update the keys, but it seems like there ought to be a better way.
Thank you very much for your assistance.
When you insert to the first table, you use the OUTPUT clause to pull the identity value and then you can use it to insert to the child table.
You can also use scope_identity() to do the same thing, but OUTPUT is the preferred method. Do not under any circumstances use ##Identity as it often will give incorrect results and mess up your data integrity.
Look up how to use them in Books Online.

Resources