How to add values of primary key column into foreign key column of other table - sql

How to add values of primary key column into foreign key column of other table: I'm using SQL Server 2012
CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL,
ADDRESS CHAR (25) , SALARY DECIMAL (18, 2), PRIMARY KEY (ID));
CREATE TABLE ORDERS ( ID INT NOT NULL, DATE DATETIME, CUSTOMER_ID INT references
CUSTOMERS(ID), AMOUNT VARCHAR (255), PRIMARY KEY (ID));
Here i need to take all values from primary key table 'customers' from column 'ID' to foreign key table orders to column 'ID'
DECLARE #A INT, #DATE DATETIME, #C_ID INT, #AMOUNTS INT;
SET #A =1;
SET #DATE ='2009-10-08 00:00:00';
SET #C_ID = 100
SET #AMOUNTS=1000;
WHILE #A <= 7
BEGIN
SET #DATE = DATEADD(DAY,1,#DATE);
SET #C_ID = #C_ID + 1
SET #AMOUNTS = #AMOUNTS+100;
INSERT INTO ORDERS(ID, DATE, CUSTOMER_ID,AMOUNT)
SELECT ID, #DATE, #C_ID, #AMOUNTS FROM CUSTOMERS WHERE AGE like'%';
SET #A = #A+1;
END

You have set your Orders table up with a Foreign Key on Customer_ID that references Customers(ID). So you can you only add rows to Orders if the ID exists in Customers. Right now you are trying to insert 101-107 in that column every time, so check if those IDs exists in Customers.
It seems to me that you SHOULD want to insert the Customers.ID column in Orders.Customer_ID, rather than Orders.ID. Is that what you meant?

Related

What is the mistake in this SQL statement? - SQL

SQL query:
insert into Transaction_Details (Trans_Date, Trans_Type)
values (GetDate(), 'WITHDRWAL')
from Transaction_Details t
inner join Acc_Details a on t.UserID = a.UderId
where a.Card_No = '1234567890123456';
Transaction table columns:
Trans_ID int PRIMARY KEY IDENTITY(1,1),
Trans_Date datetime,
Trans_Type varchar(20),
UserID int foreign key references User_Details(UserID)
Card_Id varchar(16) foreign key references User_Card_Details,
Acc_No int foreign key references Acc_Details(Acc_No)
Acc_Details columns:
Acc_Id int,
Acc_No int PRIMARY KEY,
Card_No varchar(16) foreign key references User_Card_Details(Card_No),
UserId int foreign key references User_Details(UserID),
Balance int,
BankName varchar(15)
I get this error:
Incorrect syntax near the keyword 'from'
To insert based on a select it's this:
insert into Transaction_Details (Trans_Date, Trans_Type)
select GetDate(),
'WITHDRWAL'
from Transaction_Details t
inner join Acc_Details a on t.UserID = a.UderId
where a.Card_No = '1234567890123456';

how to add a database constraint 18 or above

i have create a table and I need to add a database constraint "A customer with an age under 18 cannot rent a movie rated “18 or above”." How do I use SQL to add this in my table
You can use a trigger. When you want to enter information in the system to order a movie, do not allow the user to create a record if the age is less than the minimum required.
The following code snippet implements this scenario completely.
CREATE TABLE Customers
(
ID int identity,
FirstName nvarchar(100),
LastName nvarchar(100),
Age int,
primary key(ID))
CREATE TABLE Films
(
ID int identity,
FilmName nvarchar(100),
MinimumAge int,
primary key(ID))
CREATE TABLE OrderFilms
(
ID int identity,
CustomerID int,
FilmID int,
primary key(ID),
foreign key(CustomerID) references Customers,
foreign key(FilmID) references Films)
create trigger trigger_for_insert_into_OrderFilms
On OrderFilms
For Insert
AS
Declare #film int
Declare #customer int
Declare #filmage int
Declare #customerage int
set #film = (SELECT top 1 FilmID FROM inserted)
set #customer = (SELECT top 1 CustomerID FROM inserted)
set #filmage = (SELECT MinimumAge FROM Films WHERE ID = #film)
set #customerage = (SELECT Age FROM Customers WHERE ID = #customer)
IF(#filmage > 18 AND #customerage < 18)
BEGIN
PRINt 'ERROR, CUSTOMER AGE THE CUSTOMER IS YOUNG'
RollBack
END

How to use parameters in select query?

I have table :
Table Name : tbl_Income
EmployeeID Element FinancialYear Jan Feb Mar
00402060 Basic 2016-2017 100 200 300
00402060 HRA 2016-2017 100 200 300
00402060 DA 2016-2017 100 200 300
In which i want to fetch data from tbl_Income.
In which i fetch below problem.
Declare #Month varchar(10) = 'Jan'
select #Month from tbl_Income where EmployeeID = '00402060' and Element = 'Basic' and FinancialYear = '2016-2017'
I want to below Output
OUTPUT :
Jan
1 100
Please help me...
You can use Dynamic SQL like this:
declare #sql nvarchar(max)
Declare #Month varchar(10) = 'Jan'
declare #income int
set #sql = 'select #inc=' + #Month + ' from tbl_Income where EmployeeID = ''00402060'' and Element = ''Basic'' and FinancialYear = ''2016-2017'''
exec sp_executesql #sql, N'#inc int OUTPUT', #inc=#income OUTPUT
select #income as income
Beware though that this is open to SQL Injection attack.
You'd be better off fixing your design.
[Sample Database Design][1]
[1]: https://i.stack.imgur.com/2vxEb.png
-- table "dbo.Month"
CREATE TABLE dbo.Month (
Id int NOT NULL,
Name nvarchar(50) NOT NULL,
CONSTRAINT PK_Month PRIMARY KEY CLUSTERED (Id)
)
-- table IncomeType"
CREATE TABLE dbo.IncomeType (
Id int NOT NULL,
Name nvarchar(50) NOT NULL,
CONSTRAINT PK_IncomeType PRIMARY KEY CLUSTERED (Id)
)
-- table "FinancialYear"
CREATE TABLE dbo.FinancialYear (
Id int NOT NULL,
YearSpan nvarchar(50) NOT NULL,
CONSTRAINT PK_FinancialYear PRIMARY KEY CLUSTERED (Id)
)
-- table "Employee"
CREATE TABLE dbo.Employee (
Id int NOT NULL,
Name nvarchar(50) NOT NULL,
CONSTRAINT PK_Employee PRIMARY KEY CLUSTERED (Id)
)
-- table "Income"
CREATE TABLE dbo.Income (
Id int NOT NULL,
EmployeeId int NOT NULL,
TypeId int NOT NULL,
YearSpanId int NOT NULL,
MonthId int NOT NULL,
CONSTRAINT PK_Income PRIMARY KEY CLUSTERED (Id)
)
--Alter Each Table to add foreign key references
ALTER TABLE Income
ADD CONSTRAINT FK_Income_Employee FOREIGN KEY (EmployeeId) REFERENCES Employee (Id)
ALTER TABLE dbo.Income
ADD CONSTRAINT FK_Income_FinancialYear FOREIGN KEY (YearSpanId) REFERENCES dbo.FinancialYear (Id)
ALTER TABLE dbo.Income
ADD CONSTRAINT FK_Income_IncomeType FOREIGN KEY (TypeId) REFERENCES dbo.IncomeType (Id)
ALTER TABLE dbo.Income
ADD CONSTRAINT FK_Income_Month FOREIGN KEY (MonthId) REFERENCES dbo.Month (Id)
EmployeeID will come from the Employee table
Element will come from the income type table
FinancialYear --from the financial year table
MonthId from the months table
Now a simple join can help you get each value using the foreign key references
Declare #Month varchar(10) = 'Jan'
declare #v nvarchar(max)
declare #v1 INT
set #v =CONCAT('select #v1=' ,#month, ' from
table_a where EmployeeID = ''00402060'' and Element = ''Basic'' and FinancialYear = ''2016-2017''')
PRINT #V
EXECUTE sp_executesql #v,N'#V1 INT OUTPUT', #V1=#V1 OUTPUT;
SELECT #V1;

Stored procedure to insert a list of different types of items in to a table

I have following two tables
CREATE TABLE Orders
(
OrderID int IDENTITY NOT NULL,
StaffID int NOT NULL,
TotalPrice money NOT NULL,
OrderDateTime dateTime NOT NULL
PRIMARY KEY (OrderID),
FOREIGN KEY (StaffID)
REFERENCES Staff(StaffID)
)
CREATE TABLE OrderDetails
(
OrderDetailID int IDENTITY NOT NULL,
OrderID int NOT NULL,
ItemID int,
ExtrasID int,
ItemQuantity int,
ExtrasQuantity int
PRIMARY KEY (OrderDetailID)
FOREIGN KEY (OrderID)
REFERENCES Orders(OrderID),
FOREIGN KEY (ExtrasID)
REFERENCES Extras(ExtrasID),
FOREIGN KEY (ItemID)
REFERENCES Item(ItemID)
)
I would like to create a stored procedure which will create a new order by inserting data in to both tables. This procedure should take the parameters for the StaffID, TotalPrice and the bought products. Products can be a many Items, many Extras or both.
Is there any way I can have a list of ItemID's and a list of ExtrasID's as the parameters which will then be inserted in to the OrderDetails table correctly?
Create a type first
CREATE TYPE dbo.ty_Product_Orders AS Table
(
ItemID INT
,ExtrasID INT
,ItemQuantity INT
,ExtrasQuantity INT
)
GO
Procedure Definition
Now make your procedure accept a parameter of that type.
CREATE PROCEDURE usp_Place_Order
#StaffID INT
,#TotalPrice MONEY
,#Order dbo.ty_Product_Orders READONLY
,#OrderPlaced BIT = 0 OUTPUT
AS
BEGIN
SET NOCOUNT ON;
-- table variable to hold the identity values
DECLARE #OrderDetails TABLE
(
OrderID INT,
ItemID INT
,ExtrasID INT
,ItemQuantity INT
,ExtrasQuantity INT
)
BEGIN TRY
BEGIN TRANSACTION;
-- Insert Orders
INSERT INTO Orders (StaffID , TotalPrice , OrderDateTime)
OUTPUT inserted.OrderID , inserted.ItemID ,inserted.ExtrasID ,
inserted.ItemQuantity ,inserted.ExtrasQuantity
INTO #OrderDetails(OrderID , ItemID , ExtrasID
,ItemQuantity ,ExtrasQuantity)
SELECT #StaffID , #TotalPrice , GETDATE()
FROM #Order
-- insert OrderDetails
INSERT INTO OrderDetails ((OrderID , ItemID , ExtrasID ,ItemQuantity ,ExtrasQuantity)
SELECT OrderID , ItemID , ExtrasID,ItemQuantity ,ExtrasQuantity
FROM #OrderDetails
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF (##TRANCOUNT <> 0)
ROLLBACK TRANSACTION;
-- Other error logging here
END CATCH
END

How to insert data to multiple tables in C#

CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
CREATE TABLE ORDERS (
ID INT NOT NULL,
DATE DATETIME,
CUSTOMER_ID INT references CUSTOMERS(ID),
AMOUNT VARCHAR (255),
PRIMARY KEY (ID)
);
I want to insert data into both table at a time, i.e. inserting the ID from table CUSTOMERS into Customer_ID in table ORDERS.
Please help me!
TRY THIS
DECLARE #CustomerID INT
INSERT INTO Customer ...
SELECT #CustomerID = SCOPE_IDENTITY() FROM Customer
You'll get the last inserted customer ID and then insert to order table.