I am working on an event management project. In that project, I have a form in admin panel as add event which contains events name, category, sub-category, event admin etc and more. And in the database, I have different tables like event category, event sub-category.
And also I have a table that is cultural event which includes form fields and foreign key. I pass event catid, event sub-cat id.
On button click that cultural event is added.
I want to insert data in their tables and I want id that I gave in cultural event table.
On single click I want to insert this
How can I achieve this? Using a stored procedure?
CREATE TABLE EVENT_SCAT (ESUBCAT_ID INT NOT NULL PRIMARY KEY, ECAT_ID INT NOT NULL FOREIGN KEY REFERENCES EVENT_CAT(ECAT_ID), ESUBCAT_NAME VARCHAR(255) NOT NULL, )
create table EVENT_CAT (ECAT_ID INT NOT NULL IDENTITY PRIMARY KEY, ECAT_NAME VARCHAR(255)NOT NULL, EID INT NOT NULL FOREIGN KEY REFERENCES EVENTDETAILS(EID)
CREATE TABLE Cultural_E (c_ID INT NOT NULL IDENTITY PRIMARY KEY, cEVENT_NAME VARCHAR(255) NOT NULL, cE_SDATE DATE NOT NULL, cE_EDATE DATE NOT NULL, SE_RULES1 VARCHAR(MAX), SE_RULES2 VARCHAR(MAX), SE_RULES3 VARCHAR(MAX), cE_RULES4 VARCHAR(MAX), cE_EFEES INT, EID INT NOT NULL FOREIGN KEY REFERENCES EVENTDETAILS(EID), ECAT_ID INT NOT NULL FOREIGN KEY REFERENCES EVENT_CAT(ECAT_ID) )
and i have form in asp.net which includes all fields in single form but there are different tables with foreign keys. and i want id of ecat id and subcatid in last table i.e Cultural_e.
for ex:THESE ARE TABLE
eVENT_T
ID ENAME EADMIN
1 CULTURAL NIKHIL
E_CAT
ID ECAT_NAME E_iD
1 SINGING 1
event_scat
ID eCAT_iD ESUBCAT_NAME
1 1 SOLO
NOW I HAVE TABLE THAT IS CULTURAL_T
THESE TABLE HAVE ITS OWN FILEDS AS WELL AS FOREIGN KEY LIKE EID ,ECAT_ID AS YOU CAN SEE ABOVE
AND I HAVE FORM IN ASP.NET AND FORM CONTAINS TEXTBOX TO ENTER DATA OF ALL THESE TABLE.
SO PLZ TELL ME HOW TO ACHIEVE THIS
THANK YOU
As per my understanding of your question,try to use triggers rather than stored procedures if possible.
CREATE TRIGGER InsertEvents
AFTER INSERT ON EVENT_CAT
BEGIN
/* Insert Query to EVENT_SCAT */
/* Insert Query to cultural */
END
Related
Example; 3 Tables.
Table1 = Forms - (key) FormID int, FormName nvchar(30), Required bit, IsActive bit, IsDeleted bit
Table2 = FormLabel - (key) FormLabelId int, FormID int, LabelName nvhcar(30), IsActive bit, isDeleted bit, CustomeField nvchar(30), DisplayOrder int
Table3 = FormEntry - (key) EntryID int, FormID int, FormLabelID int, EntryName nvchar(max), IsActive bit, IsDeleted bit, DisplayOrder int
I need to create a Form, Then use that Form's FormID then be used as a Reference to Create a Label, and then using the created FormLabelId create X entries referencing both FormID + FormLabelId
There will likely be multiple FormEntry(s) to be inserted per Label per Form.
Example;
Create a new Form that with have 5 Labels, each with 5 Entries.
Form1 -> Label1 -> Entry1-5.
Form2 -> Label2 -> Entry1-5 etc.
I guess your looking for a nested relationship among three (3) tables: Forms, FormLabel and FormEntry. Each one has a unique primary key and the relationship could be depicted as:
Forms is the parent entity.
FormLabel seeks Label registers from Forms table.
FormEntry checks registers from FormLabel table and, also from Forms table.
In this way, a SQL script may be used with above mentioned entities as follows, supposing if you have a database called MYAPP in plain SQL ANSI already in a SQL Server on Premise or in a SQL Azure database engine:
create Table Forms (
FormID int not null,
FormName nvarchar(30),
IsRequired bit,
IsActive bit,
IsDeleted bit
CONSTRAINT PK_FormID PRIMARY KEY CLUSTERED (FormID)
) on [PRIMARY];
create Table FormLabel (
FormLabelId int not null,
FormID int,
LabelName nvarchar(30),
IsActive bit,
isDeleted bit,
CustomeField nvarchar(30),
DisplayOrder int,
CONSTRAINT PK_FormLabelId PRIMARY KEY CLUSTERED (FormLabelId)
) on [PRIMARY];
create Table FormEntry (
EntryID int not null,
FormID int,
FormLabelID int,
EntryName nvarchar(max),
IsActive bit,
IsDeleted bit,
DisplayOrder int
CONSTRAINT PK_EntryID PRIMARY KEY CLUSTERED (EntryID)
) on [PRIMARY];
So, the approach for Foreign Keys on
FormLabelId create X (or n) entries referencing both FormID + FormLabelId
that are you wrote could be generated with a set of Foreign Keys for FormID and for FormLabelId specified in the table FormEntry:
/* FormEntry */
alter table FormEntry
add constraint fk_FormLabelID foreign key (FormLabelID)
references FormLabel (FormLabelId)
constraint fk_FormEntry_FormID foreign key (FormID)
references Forms (FormID)
;
This looks like:
However, in the example
Create a new Form that with have 5 Labels, each with 5 Entries. Form1 -> Label1 -> Entry1-5. Form2 -> Label2 -> Entry1-5
You specify to create 5 Labels, thus, they're 5 registers on table FormLabel with 5 registers on FormEntry table, but no integrity rules are cleared here. The insight is used as follows with the same script with a light modification:
/* FormLabel */
alter table FormLabel
add constraint fk_FormID foreign key (FormID)
references Forms (FormID)
ON UPDATE CASCADE
;
Where the keyword CASCADE is corresponding rows are updated in the referencing table (in this case, FormLabel) when that row is updated in the parent table (Forms).
So, I hope for your feedback is this worth.
I'm designing a new database for a company, trying to keep strict constraints with foreign keys etc for integrity. I have a table [Member] which holds companies on the system. This table has a column of [internalContact] for the user in our company who deals with this member which has a foreign linked to the users table by user id.
What I would like to know is if it is possible to assign a condition to the foreign key, since the users table contains internal and external users. ie. for the field to only accept a user id where the user type is 5. Can this be done, or can I only control this in my application code?
Thanks
You can use a check constraint for this.
(The code is untested some syntax errors will be in there)
CREATE TABLE Member
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
InternalContactId
CONSTRAINT chk_Person CHECK (isInternalUser(internalContactId) > 0)
)
ALTER TABLE Member
ADD FOREIGN KEY (InternalContacId)
REFERENCES Persons(P_Id)
Then just create a function isInternalUser that returns 1 if user in ok to be an internal contact
CREATE FUNCTION isInternalUser ( #userId int(10) )
RETURNS int
AS
BEGIN
DECLARE #tmp int
SELECT #tmp = count(*)
FROM users
WHERE userId = #UserId and <check to see if user is internal>
RETURN(#CtrPrice)
END
GO
Im a beginner in database and i got this difficult auction database project.
Im using SQL Server Management Studio also.
create table user(
name char(10) not null,
lastname char(10) not null
)
create table item(
buyer varchar(10) null,
seller varchar(10) not null,
startprice numeric(5) not null,
description char(22) not null,
start_date datetime not null,
end_date datetime not null,
seller char(10) not null,
item_nummer numeric(9) not null,
constraint fk_user foreign key (buyer) references user (name)
)
Basically what the rule im trying to make here is:
Column buyer has NULL unless the time (start_date and end_date) is over and startprice didnt go up or increased. Then column buyer will get the name from table user who bidded on the item.
The rule is a bid too difficult for me to make, i was thinking to make a trigger, but im not sure..
Your model is incorrect. First you need a table to store the bids. Then when the auction is over, you update the highest one as the winning bid. Proably the best way is to have a job that runs once a minute and finds the winners of any newly closed auctions.
A trigger will not work on the two tables you have because triggers only fire on insert/update or delete. It would not fire because the time is past. Further triggers are an advanced technique and a db beginner should avoid them as you can do horrendous damage with a badly written trigger.
You could have a trigger that works on insert to the bids table, that updates the bid to be the winner and takes that status away from the previous winner. Then you simply stop accepting new bids at the time the auction is over. Your application could show the bidder who is marked as the winner as the elader if the auction is till open and teh winner if it is closed.
There are some initial problems with your schema that need addressed before tackling your question. Here are changes I would make to significantly ease the implementation of the answer:
-- Added brackets around User b/c "user" is a reserved keyword
-- Added INT Identity PK to [User]
CREATE TABLE [user]
(
UserId INT NOT NULL
IDENTITY
PRIMARY KEY
, name CHAR(10) NOT NULL
, lastname CHAR(10) NOT NULL
)
/* changed item_nummer (I'm not sure what a nummer is...) to ItemId int not null identity primary key
Removed duplicate Seller columns and buyer column
Replaced buyer/seller columns with FK references to [User].UserId
Add currentBid to capture current bid
Added CurrentHighBidderId
Added WinningBidderId as computed column
*/
CREATE TABLE item
(
ItemId INT NOT NULL
IDENTITY
PRIMARY KEY
, SellerId INT NOT NULL
FOREIGN KEY REFERENCES [User] ( UserId )
, CurrentHighBidderId INT NULL
FOREIGN KEY REFERENCES [User] ( UserId )
, CurrentBid MONEY NOT NULL
, StartPrice NUMERIC(5) NOT NULL
, Description CHAR(22) NOT NULL
, StartDate DATETIME NOT NULL
, EndDate DATETIME NOT NULL
)
go
ALTER TABLE dbo.item ADD
WinningBidderId AS CASE WHEN EndDate < CURRENT_TIMESTAMP
AND currentBid > StartPrice THEN CurrentHighBidderId ELSE NULL END
GO
With the additional columns a computed column can return the correct information. If you must return the winner's name instead of id, then you could keep the schema above the same, add an additional column to store the user's name, populate it with a trigger and keep the computed column to conditionally show/not show the winner..
Are Foreign Keys in SQL Server 2008 are automatically indexed with a value? For Example. if I add a value in my Primary key (or auto incremetend) in may parent table will the table that has a foreign key referenced to that key will automatically have the same value? or I Have to do it explicitly?
No, if you create a foreign key in a child table, it will not automatically get populated when a parent row gets inserted. If you think about this it makes sense. Let's say you have a table like:
CREATE TABLE dbo.Students
(
StudentID INT IDENTITY(1,1) PRIMARY KEY,
Name SYSNAME
);
CREATE TABLE dbo.StudentLoans
(
LoanID INT IDENTITY(1,1) PRIMARY KEY,
StudentID INT FOREIGN KEY REFERENCES dbo.Students(StudentID),
Amount BIGINT -- just being funny
);
What you are suggesting is that when you add a row to Students, the system should automatically add a row to StudentLoans - but what if that student doesn't have a loan? If the student does have a loan, what should the amount be? Should the system pick a random number?
Typically what will happen in this scenario is that you'll be adding a student and their loan at the same time. So if you know the loan amount and the student's name, you can say:
DECLARE
#Name SYSNAME = N'user962206',
#LoanAmount BIGINT = 50000,
#StudentID INT;
INSERT dbo.Students(Name)
SELECT #Name;
SELECT #StudentID = SCOPE_IDENTITY();
INSERT dbo.StudentLoans(StudentID, Amount)
SELECT #StudentID, #LoanAmount;
I need help in auto populating the primary key values in foreign key table while inserting data in foreign key table. For Example: I have created table:
create table Patient
(
PatientId int IDENTITY(1,1) primary key,
FirstName varchar(50),
SurName varchar(50),
Gender char(20),
)
Say 5 rows are there in this Patient Table:
Say First Row value is: 1, Priya, Kumari, Female
I have created the Guardians Table:
create table Guardians
(
GuardiansId int identity(1,1) primary key,
PatientId int foreign key references Patient(PatientId),
FirstName varchar(50),
SurName varchar(50),
Gender char(20),
RelationToPatient varchar(50),
)
In this table Insert operations are like this:
insert into Guardians(FirstName, SurName, Gender,RelationToPatient)values('Sumit','Kumar','Male','Wife')
While selecting the Guardians Table PatientId showing NULL values: My query is while inserting the values in Guardians Table PatientId should be auto Populated which will come from Patient Table...
My second problem is: How to create the Identity column as varchar. For example: suppose I want to increment my Guardians Table with 'GRD0001', 'GRD0002', 'GRD0003' like this...
Thanks,
S.D
Your question is not very clear - what exactly do you want to do??
When you insert something into the Guardians table, you want to automatically also insert it into the Patients table? I don't quite follow. Can you make a complete example, maybe??
If you need to capture the insert IDENTITY value from the Patient table, do this:
DECLARE #NewPatientID INT
INSERT INTO dbo.Patient(fields) VALUES(.......)
SET #NewPatientID = SCOPE_IDENTITY()
INSERT INTO dbo.Guardians(PatientId, ......) VALUES(#NewPatientID, ......)
As for your second question: leave you GuardiansId IDENTITY as it is (only an INT column can be an IDENTITY and you want to keep that - trust me!) and add a computed column to your table:
ALTER TABLE dbo.Guardians
ADD GuardianIDWithPrefix AS
'GDR' + RIGHT('0000' + CAST(GuardiansId AS VARCHAR(4)), 4) PERSISTED
Since it's a PERSISTED field, you can even index on it and use it like a normal field in every respect.
That should do the trick!