CREATE TABLE DUser (
[ID] INT NOT NULL, [DUser_Id] VARCHAR(45) NULL,
[Name] VARCHAR (70) NOT NULL,
[DOB] DATE NOT NULL,
[Password] VARCHAR (30) NOT NULL,
[Email] VARCHAR (70) NOT NULL,
[Phone_Number] INT NOT NULL,
[Gender] VARCHAR (6) NOT NULL, PRIMARY KEY CLUSTERED ([ID] ASC) );
Create TRIGGER DUser_IDColumn
ON DUser
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
UPDATE duserid SET
DUser_ID = 'U' + LEFT('0000' + CAST(inserted.ID AS VARCHAR(10)), 5) FROM DUser duserid
INNER JOIN inserted
ON duserid.ID = inserted.ID
END GO
The ID starts at U00000, when I want it to start from U00003, as there are pre-defined values.
PLEASE I NEED HELP!!
When I Create an user account
Looks like you need to reseed your AUTO-INCREMENT like below using ALTER statement
ALTER TABLE DUser AUTO_INCREMENT = 1
From your posted code, I don't see that it's a autoincrement column at all. Then there is no way you can expect it to start from 1. It's looks like custom identity column.
CREATE TABLE DUser (
[ID] INT NOT NULL
Can't you, in you script where you create the table "DUser" put something like
`AUTO_INCREMENT=3`
?
So It will be something like
CREATE TABLE DUser (
[ID] INT NOT NULL,
[DUser_Id] VARCHAR(45) NULL,
[Name] VARCHAR (70) NOT NULL,
[DOB] DATE NOT NULL,
[Password] VARCHAR (30) NOT NULL,
[Email] VARCHAR (70) NOT NULL,
[Phone_Number] INT NOT NULL,
[Gender] VARCHAR (6) NOT NULL, PRIMARY KEY CLUSTERED ([ID] ASC) )
ENGINE=InnoDB AUTO_INCREMENT=3;
Related
I have a users table in my database which has a foreign key for Packages (PackageId), I want a query in which I can retrieve the specific package details for that one user.
So in theory I need to retrieve that users PackageId from the table then output that particular package into my Data grid. Another issue is that I need to verify which user is logged into the application as well to specify which users package details will be output in the grid.
Here is my working log in query which only takes email as verification.
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
try
{
con.Open();
string query = "SELECT COUNT(1) from AspNetUsers WHERE Email=#Email";
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Email", txtUsername.Text);
int count = Convert.ToInt32(cmd.ExecuteScalar());
if (count == 1)
{
MainWindow mainWindow = new MainWindow();
mainWindow.Show();
this.Close();
}
else
{
MessageBox.Show("Incorrect Login Information");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
Here is my users table Code:
CREATE TABLE [dbo].[AspNetUsers] (
[Id] NVARCHAR (450) NOT NULL,
[APIKey] UNIQUEIDENTIFIER NULL,
[AccessFailedCount] INT NOT NULL,
[AccountType] NVARCHAR (MAX) NULL,
[ConcurrencyStamp] NVARCHAR (MAX) NULL,
[Email] NVARCHAR (256) NULL,
[EmailConfirmed] BIT NOT NULL,
[FirstName] NVARCHAR (MAX) NULL,
[LastName] NVARCHAR (MAX) NULL,
[Locations] INT NOT NULL,
[LockoutEnabled] BIT NOT NULL,
[LockoutEnd] DATETIMEOFFSET (7) NULL,
[NormalizedEmail] NVARCHAR (256) NULL,
[NormalizedUserName] NVARCHAR (256) NULL,
[PackageId] INT NULL,
[PasswordHash] NVARCHAR (MAX) NULL,
[PeriodOrderQty] INT NULL,
[PhoneNumber] NVARCHAR (MAX) NULL,
[PhoneNumberConfirmed] BIT NOT NULL,
[Qualifications] INT NOT NULL,
[SecurityStamp] NVARCHAR (MAX) NULL,
[TotalOrderQty] INT NULL,
[TwoFactorEnabled] BIT NOT NULL,
[UserName] NVARCHAR (256) NULL,
CONSTRAINT [PK_AspNetUsers] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_AspNetUsers_Packages_PackageId] FOREIGN KEY ([PackageId]) REFERENCES [dbo].[Packages] ([Id])
);
GO
CREATE NONCLUSTERED INDEX [EmailIndex]
ON [dbo].[AspNetUsers]([NormalizedEmail] ASC);
GO
CREATE UNIQUE NONCLUSTERED INDEX [UserNameIndex]
ON [dbo].[AspNetUsers]([NormalizedUserName] ASC) WHERE ([NormalizedUserName] IS NOT NULL);
GO
CREATE NONCLUSTERED INDEX [IX_AspNetUsers_PackageId]
ON [dbo].[AspNetUsers]([PackageId] ASC);
Here is my packages code:
CREATE TABLE [dbo].[Packages] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Cost] DECIMAL (18, 2) NOT NULL,
[OrderLimit] INT NOT NULL,
[PackageName] NVARCHAR (MAX) NULL,
[ResetInterval] INT NOT NULL,
[ResetIntervalType] NVARCHAR (MAX) NULL,
CONSTRAINT [PK_Packages] PRIMARY KEY CLUSTERED ([Id] ASC)
);
The only connection right now is that User01 in the users table is connected to packageId = "1".
This query worked and output the correct package.
"SELECT p.* FROM AspNetUsers as u JOIN packages as p ON u.package_id = p.id WHERE Email = #Email";
I'm creating the following table:
CREATE TABLE [dbo].[Symptoms]
(
[Id] INT NOT NULL,
[description] NVARCHAR (128) NOT NULL,
[imgPath] NVARCHAR (128) NOT NULL,
[diseaseId] INT NOT NULL,
[weight] FLOAT NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC, [diseaseId] ASC)
);
What I want to do is create a default value for the [imgPath] column. I know about DEFAULT newid() and other methods, but I want a custom generated method.
Specifically, I want the [imgPath] to be $"/resources/Images/{Id}_symptom.jpg" where Id is the ID of that specific row.
Where can I specify this function?
Thanks!
Update
Column defaults in SQL Server can't be made up using other columns data.
What you can do is add another column for you to specify the image path, and use it as a part of the computed column's declaration:
CREATE TABLE [dbo].[Symptoms] (
[Id] INT NOT NULL,
[description] NVARCHAR (128) NOT NULL,
[UserDefinedImgPath] NVARCHAR (128) NULL,
[imgPath] AS COALESCE(UserDefinedimgPath, '/resources/Images/' + CAST(Id AS NVARCHAR(13)) +'_symptom.jpg') PERSISTED,
[diseaseId] INT NOT NULL,
[weight] FLOAT NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC, [diseaseId] ASC)
);
Now, when you want to specify the image page on insert or update, use the UserDefinedImgPath column. When you want the default value, simply leave it null.
When selecting the image path, always use the computed column.
First answer
Use a computed column for imgPath:
CREATE TABLE [dbo].[Symptoms] (
[Id] INT NOT NULL,
[description] NVARCHAR (128) NOT NULL,
[imgPath] AS '/resources/Images/' + CAST(Id AS NVARCHAR(13)) +'_symptom.jpg' PERSISTED,
[diseaseId] INT NOT NULL,
[weight] FLOAT NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC, [diseaseId] ASC)
);
Note that you can't update a computed column, nor can you insert a specific value to it.
To add default value please create default constraint, in SQL Server the example is below:
ALTER TABLE Symptoms
ADD CONSTRAINT Symptoms_imgPath
DEFAULT (('/resources/Images/{Id}_symptom.jpg')) FOR imgPath
Other way is to insert default value at the time of insert, like this:
INSERT INTO Symptoms
SELECT '/resources/Images/{Id}_symptom.jpg'
FROM symptoms
WHERE id = NEWID()
I am in the process of building the website for the Linq, and the way that I need is to use Foreign keys to precisely set the same with my users table.ยจ
I have assured me that my Tabler has a primary key because it must be unique content that use grab.
Its a brugere table
CREATE TABLE [dbo].[brugere] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[username] NVARCHAR (255) NOT NULL,
[password] NVARCHAR (255) NOT NULL,
CONSTRAINT [PK_brugere] PRIMARY KEY ([Id]),
CONSTRAINT [FK_brugere_ToPoint] FOREIGN KEY ([Id]) REFERENCES [pointantal]([brugerid]),
CONSTRAINT [FK_brugere_ToKunde] FOREIGN KEY ([Id]) REFERENCES [KundeData]([brugerid])
);
Poinantal its here
CREATE TABLE [dbo].[pointantal] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[point] INT NOT NULL,
[omrade] NVARCHAR (255) NOT NULL,
[datotid] DATETIME DEFAULT (getdate()) NOT NULL,
[brugerid] INT NOT NULL,
CONSTRAINT [PK_pointantal] PRIMARY KEY ([Id])
);
and KundeData table here
CREATE TABLE [dbo].[KundeData] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Adresse] NVARCHAR (255) NOT NULL,
[Postnr] INT NOT NULL,
[Mobil] INT NOT NULL,
[Byen] NVARCHAR (255) NOT NULL,
[abonnementsId] INT NOT NULL,
[BuyDate] DATETIME DEFAULT (getdate()) NOT NULL,
[prisid] INT NOT NULL,
[HaevedeId] NVARCHAR (255) NULL,
[brugerid] INT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
The error message I receive when I try to updater content is here
Update cannot proceed due to validation errors.
Please correct the following errors and try again.
SQL71516 :: The referenced table '[dbo].[pointantal]' contains no
primary or candidate keys that match the referencing column list in
the foreign key. If the referenced column is a computed column, it
should be persisted. SQL71516 :: The referenced table
'[dbo].[KundeData]' contains no primary or candidate keys that match
the referencing column list in the foreign key. If the referenced
column is a computed column, it should be persisted.
A foreign key can only reference a primary key or unique column. You can either add a unique constraint to the columns that you are referencing:
CREATE TABLE [dbo].[pointantal] (
...
CONSTRAINT AK_BrugerID UNIQUE(brugerid)
Or you can change your constraint to actually reference the primary key in your tables:
CONSTRAINT [FK_brugere_ToPoint] FOREIGN KEY ([Id]) REFERENCES [pointantal]([Id])
However, it seems like you really want the brugerid column of the pointantal and KundeData tables to access an Id (which is a unique column) in the brugere table. In this case, you put the foreign key on those tables and have it access the primary key of the bruger table. The following code runs sucessfully on my system:
CREATE TABLE [dbo].[brugere] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[username] NVARCHAR (255) NOT NULL,
[password] NVARCHAR (255) NOT NULL,
CONSTRAINT [PK_brugere] PRIMARY KEY ([Id])
);
CREATE TABLE [dbo].[pointantal] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[point] INT NOT NULL,
[omrade] NVARCHAR (255) NOT NULL,
[datotid] DATETIME DEFAULT (getdate()) NOT NULL,
[brugerid] INT NOT NULL,
CONSTRAINT [PK_pointantal] PRIMARY KEY ([Id]),
CONSTRAINT [FK_point_ToBrugere] FOREIGN KEY ([brugerid]) REFERENCES [brugere]([Id])
);
a foreign key is a field (or collection of fields) in one table that
uniquely identifies a row of another table. In simpler words, the
foreign key is defined in a second table, but it refers to the primary
key in the first table.
Try:
1>Change the Reference column
CREATE TABLE [dbo].[pointantal] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[point] INT NOT NULL,
[omrade] NVARCHAR (255) NOT NULL,
[datotid] DATETIME DEFAULT (getdate()) NOT NULL,
[brugerid] INT NOT NULL,
CONSTRAINT [PK_pointantal] PRIMARY KEY ([Id])
);
CREATE TABLE [dbo].[KundeData] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Adresse] NVARCHAR (255) NOT NULL,
[Postnr] INT NOT NULL,
[Mobil] INT NOT NULL,
[Byen] NVARCHAR (255) NOT NULL,
[abonnementsId] INT NOT NULL,
[BuyDate] DATETIME DEFAULT (getdate()) NOT NULL,
[prisid] INT NOT NULL,
[HaevedeId] NVARCHAR (255) NULL,
[brugerid] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Id])
);
CREATE TABLE [dbo].[brugere] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[username] NVARCHAR (255) NOT NULL,
[password] NVARCHAR (255) NOT NULL,
CONSTRAINT [PK_brugere] PRIMARY KEY ([Id]),
CONSTRAINT [FK_brugere_ToPoint] FOREIGN KEY ([Id]) REFERENCES [pointantal]([Id]),
CONSTRAINT [FK_brugere_ToKunde] FOREIGN KEY ([Id]) REFERENCES [KundeData]([Id])
);
2>Change The Primary-Key
CREATE TABLE [dbo].[pointantal] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[point] INT NOT NULL,
[omrade] NVARCHAR (255) NOT NULL,
[datotid] DATETIME DEFAULT (getdate()) NOT NULL,
[brugerid] INT NOT NULL,
CONSTRAINT [PK_pointantal] PRIMARY KEY ([brugerid])
);
CREATE TABLE [dbo].[KundeData] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Adresse] NVARCHAR (255) NOT NULL,
[Postnr] INT NOT NULL,
[Mobil] INT NOT NULL,
[Byen] NVARCHAR (255) NOT NULL,
[abonnementsId] INT NOT NULL,
[BuyDate] DATETIME DEFAULT (getdate()) NOT NULL,
[prisid] INT NOT NULL,
[HaevedeId] NVARCHAR (255) NULL,
[brugerid] INT NOT NULL,
PRIMARY KEY CLUSTERED ([brugerid])
);
CREATE TABLE [dbo].[brugere] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[username] NVARCHAR (255) NOT NULL,
[password] NVARCHAR (255) NOT NULL,
CONSTRAINT [PK_brugere] PRIMARY KEY ([Id]),
CONSTRAINT [FK_brugere_ToPoint] FOREIGN KEY ([Id]) REFERENCES [pointantal]([brugerid]),
CONSTRAINT [FK_brugere_ToKunde] FOREIGN KEY ([Id]) REFERENCES [KundeData]([brugerid])
);
I have two table Users and Appointements.
In the User table I got the following fields:
Id_user, email, lastName, FirstName, hash, salt.
I put a CONSTRAINT [UNQ_email] UNIQUE NONCLUSTERED ([email] ASC).
In the Appointement I got the following fields:
Id_Appointement, doctorName, date_App, time_App, patientLstName, patientFirstName, patientFirstName, IsAvailable, email.
I put a CONSTRAINT [fk_emailPatient] FOREIGN KEY ([emailPatient]) REFERENCES [dbo].[User] ([email])
I will like to do something similar to this but with the lastName and FirstName.
Any idea on how to do this since there are not a KEY. Which constraint I can put in this case?
Here are the table definitions:
CREATE TABLE [dbo].[Users] (
[Id_user] INT IDENTITY (1, 1) NOT NULL,
[email] NVARCHAR (50) NOT NULL,
[hash] NVARCHAR (50) NOT NULL,
[salt] NVARCHAR (50) NOT NULL,
[lastName] NVARCHAR (50) NULL,
[firstName] NVARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([Id_user] ASC),
CONSTRAINT [UNQ_email] UNIQUE NONCLUSTERED ([email] ASC)
);
CREATE TABLE [dbo].[Apointement] (
[Id_Appointement] INT IDENTITY (1, 1) NOT NULL,
[doctor] NVARCHAR (50) NOT NULL,
[dateApp] DATE NOT NULL,
[heureApp] TIME (7) NOT NULL,
[patientLstName] NVARCHAR (50) NULL,
[patientFirstName] NVARCHAR (50) NULL,
[IsAvailable] BIT NULL,
[email] NVARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([rdvId] ASC),
CONSTRAINT [fk_emailPatient] FOREIGN KEY ([emailPatient]) REFERENCES [dbo].[Users] ([email])
);
I will like to add a constraint on lastName and firstName but these can be NOT unique since we can have to person with the same lastname and firstname but with a different email address.
Thanks
It may be a simple/specific question but I really need help on that. I have two tables: Entry and Comment in a SQL Server database. I want to show comment count in entry table. And of course comment count will increase when a comment is added. Two tables are connected like this:
Comment.EntryId = Entry.Id
Entry table:
CREATE TABLE [dbo].[Entry] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Subject] NVARCHAR (MAX) NOT NULL,
[Content] NVARCHAR (MAX) NOT NULL,
[Type] NVARCHAR (50) NOT NULL,
[SenderId] NVARCHAR (50) NOT NULL,
[Date] DATE NOT NULL,
[Department] NVARCHAR (50) NULL,
[Faculty] NVARCHAR (50) NULL,
[ViewCount] INT DEFAULT ((0)) NOT NULL,
[SupportCount] INT DEFAULT ((0)) NOT NULL,
[CommentCount] INT DEFAULT ((0)) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
Comment table:
CREATE TABLE [dbo].[Comment] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[EntryId] INT NOT NULL,
[SenderId] NVARCHAR (50) NOT NULL,
[Date] DATETIME NOT NULL,
[Content] NVARCHAR (MAX) NOT NULL,
[SupportCount] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
I am showing the entries in a gridview in codebehind (c#). The question is this, what should I write as a query to do this most efficiently? Thanks for help.
Try this:
select e.Id,e.date,count(*) as NumComments
from Entry e
join comment c on c.entryId=e.id
group by e.id,e.date
If there might be no comments, try the following
select e.Id,e.date,count(c.entryId) as NumComments
from Entry e
left join comment c on c.entryId=e.id
group by e.id,e.date
You can use left join for that purpose. Kindly me more specific with what fields you want in gridview
And why do you want commentcount in table (most tables have that 1-many relation and we didn't use that). If you keep that in table you have to update entry table every time when comment is made.