I want to create a table wherein the 'Id' column is combined with 'Category' column and gets stored in 'UserId' column. Here is an example.
Id Category UserId
1 STD STD1
2 NMM NMM2
3 COV COV3
I have tried something like this :
Create table tblUsers
(
Id int identity primary key,
RegId as RIGHT('0000'+CAST([Id] as varchar(5)),5),
Category nvarchar(3),
UserId CONCAT(CategoryInitials,Id)
)
but this doesnt work. So, how does that work WHILE CREATING THIS TABLE?
May be like this:
Create table tblUsers
(
Id int identity primary key,
Category nvarchar(3),
UserId as (Category + cast(Id as varchar(10)))
)
Related
I am trying to create a SQL table to store a customer id and zipcode, only these 2 columns. Combination of these 2 values makes a row unique. I have 3 options in mind but not sure which one would be efficient. I will store around 200000 rows in this table and the read operation is high and write will happen once in a day.
Select query will get all customers based on the input zipcode.
example:
Select customerid from dbo.customerzipcode where zipcode in (<multiple zipcodes>)
Option 1:
Create a table with 2 columns (customerid and zipcode)
Create a composite primary key for these 2 columns.
Option 2:
Create a table with 3 columns (id, customerid and zipcode)
id being identity and primary key
create a unique constraint for customerid and zipcode
Option 3:
Create a table with 3 columns (id, customerid and zipcode)
Create a non clustered index for zipcode alone.
Can you please share which option would be better?
Select customerid from dbo.customerzipcode where zipcode in ()
The canonical design would have an index with each column as the leading column to support efficient lookup by zipcode or by customerid, eg
create table customerzipcode
(
zipcode varchar(10) not null,
customerid int not null references customer,
constraint pk_customerzipcode primary key (zipcode,customerid),
index ix_customerzip_customerid (customerid)
)
My goal is to normalize my table. My table before normalization is called Product Specifications, to normalize it I have two other tables called buyers_table and product_table
Table "Product Specifications"
Columns: Product_id , model_number, buyer
Buyers_table
Column: Buyer_id, buyer
Product_table
product_id, model_number, buyer_id
How do I insert the buyers from my product_specification table into my product_table but have the values show up as the buyer_id value instead of buyer?
Sorry I am new to this. This is a simplified version of the database that I have set up for my company.
use this design for database
Product_buyer: Columns:Id, Product_id , Buyer_id
Buyers_table: Column: Id, Buyername
Product_table: Id, Model_number
Product_Specifications: Id,Product_id,Productname,Price
then For insert data to database
First enter the information in the Product_table table
Retrieve the latest Product_table table record and enter Id as Product_id and the other of the information in the Product_Specifications table.
Enter the buyer information in the Buyers_table table when purchasing
Product_buyer
Create tables
create table Product_table
(
Id int identity,
Model_number int,
primary key(Id));
create table Product_Specifications
(Id int identity,
Product_id int,
Productname nvarchar(150),
Price int,
primary key(ID),
foreign key(Product_id) references Product_table);
//**********************
//and define other table
//......................
Retrieve product information
select Product_table.Id,Product_table.Model_number,Product_Specifications.Productname,Productname.Price
from Product_table join Product_Specifications
on Product_table.Id = Product_Specifications.Product_id
Retrieve Product_buyer information
select Product_table.Id,Product_table.Model_number,Product_Specifications.Productname,Productname.Price,Buyers_table.Id,Buyers_table.Buyername
from Buyers_table join Product_buyer on Buyers_table.Id = Product_buyer.Buyer_id
join Product_table on Product_buyer.Product_id = Product_table.Id
join Product_Specifications on Product_table.Id = Product_Specifications.Product_id
I'm creating a table to store cars, and another table to store the time when the new car was added to the database, can someone please explain to me how to create the relationship to update time automatically when the car was created.
Create table Cars
(
CarID int Primary Key identity(1,1),
Make varchar(50),
Model varchar(50),
Colour varchar(59)
)
create Table TimeLogs
(
AddedOn SYSDATETIME(),
CarId int unique foreign key references Cars(CarId)
)
I would solve this by not using a second table for what should be a column in the Cars table. The table would be designed more appropriately like this.
Create table Cars
(
CarID int Primary Key identity(1,1),
Make varchar(50),
Model varchar(50),
Colour varchar(59),
AddedOn datetime default SYSDATETIME()
)
To automatically update one table whenever another table is updated, you need to use a TRIGGER.
You needs to use insert trigger for the same, as below
CREATE TRIGGER yourNewTrigger ON yourSourcetable
FOR INSERT
AS
INSERT INTO yourDestinationTable
(col1, col2 , col3, user_id, user_name)
SELECT
'a' , default , null, user_id, user_name
FROM inserted
go
I have a table, in which I have a column to store user name. I was stroring it as varchar of format user1,user2,user3(its not inserted by user,automatically it should get generated) So for this I need to get the max int value of users and then increment it by 1 and append it with string user and store it to the next row.
If you insist on saving the user prefix to the number, you can add an identity column, and create that user column as a computed column:
CREATE TABLE tblUsers
(
UserId int Identity(1,1) PRIMARY KEY,
UserName As 'User'+ CAST(UserId as varchar),
-- Other columns
)
This way whenever you select the UserName column it's value will be calculated.
You can also specify it as PERSISTED, meaning it's value will be saved in the database and only change if the value of one of it's components will change.
The big benefit here is that the database will handle all the hard work for you, plus uniqueness is guaranteed since it's based on the value of the primary key of the table.
Add an auto-incremented field,
CREATE TABLE Users
(
ID int NOT NULL AUTO_INCREMENT=1,
LastName varchar(255) ... ,
FirstName varchar(255) ... ,
... ,
SeqToken varchar(255)
)
Than create a trigger on insert:
The trigger will auto-generate the SeqToken field:
CREATE TRIGGER trig_insert_user
ON [Users]
AFTER INSERT
AS
UPDATE [Users]
SET SeqToken='User'+CAST(ID AS VARCHAR)
WHERE ID=INSERTED.ID
I am aware that using IDENT_CURRENT will not always return me the correct identity value (especially true in multi-threaded applications). I wanted to use SCOPE_IDENTITY() instead.
For example this is my Employee table:
create table Employee
(
ID int identity(1,1),
Name varchar(20),
SystemID int,
constraint Employee_PK primary key (ID asc)
)
I have a statement below:
alter table Employee
add constraint Employee_D1 default ident_current('Employee') for SystemID
which I need to modify to use SCOPE_IDENTITY() instead.
I tried the below:
alter table Employee
add constraint Employee_D1 default SCOPE_IDENITITY() for SystemID
This did not give any errors. But upon inserting a row, I did not see this column getting updated with the identity value. What am I doing wrong?
Note that the SystemID must not be readonly, so computed field isn't an option.
My exercise here is to try eliminating entry of wrong IDENTITY value in SystemID in case parallel processes try to insert rows.
Just re-read your answer. SystemID isn't an identity column. I don't think you can use SCOPE_IDENITITY() as it hasn't added the row and retrieved the new Identity value at the point it would need the value to save.
What you will need to do is create a trigger After Insert of the row to update the SystemId value. CREATE TRIGGER
Here's how I'd approach this problem (apologies for the poor field names, I'm not feeling inventive)
CREATE TABLE employees (
id int identity(1,1) NOT NULL
, name varchar(20) NOT NULL
, actual_system_id int NULL
, system_id As Coalesce(actual_system_id, id)
, CONSTRAINT pk_employees PRIMARY KEY (id)
)
;
INSERT INTO employees (name)
VALUES ('John')
, ('Paul')
, ('George')
, ('Ringo')
;
SELECT id
, name
, system_id
FROM employees
;
UPDATE employees
SET actual_system_id = 937
WHERE name = 'George'
;
SELECT id
, name
, system_id
FROM employees
;