How to select all relations that current user is involved in ? ASP.NET SQL Server - sql

I have this database with users and relations. I simply want to show username, firstName and lastName of all the relations that some specific (current logged in user) userID is present in. How do I do this?
This is my best try.
SELECT
UserRelationship.relationshipType,
UserRelationship.userFirstID, UserRelationship.userSecondID,
[User].username, [User].firstName, [User].lastName
FROM
[User]
INNER JOIN
UserRelationship ON [User].userID = UserRelationship.userFirstID
AND UserRelationship.relationshipType = 'friends'
OR [User].userID = UserRelationship.userSecondID
AND UserRelationship.relationshipType = 'friends'
WHERE
([User].userID = #userID)
This returns all relations, but the username, firstname and lastname of current user.
These are my tables:
CREATE TABLE [dbo].[UserRelationship]
(
[userFirstID] INT NOT NULL,
[userSecondID] INT NOT NULL,
[initiatedBy] NVARCHAR (50) NOT NULL,
[relationshipType] NVARCHAR (50) NOT NULL,
CONSTRAINT [PK_UserRelationship]
PRIMARY KEY CLUSTERED ([userFirstID] ASC, [userSecondID] ASC),
CONSTRAINT [FK_UserRelationship_userFirstID]
FOREIGN KEY ([userFirstID]) REFERENCES [dbo].[User] ([userID]),
CONSTRAINT [FK_UserRelationship_initiatedBy]
FOREIGN KEY ([initiatedBy]) REFERENCES [dbo].[User] ([username]),
CONSTRAINT [CK_UserRelationship_relationshipType]
CHECK ([relationshipType]='pending' OR [relationshipType]='friends')
);
and
CREATE TABLE [dbo].[User]
(
[userID] INT IDENTITY (1, 1) NOT NULL,
[username] NVARCHAR (50) NOT NULL,
[firstName] NVARCHAR (50) NULL,
[lastName] NVARCHAR (50) NULL,
[dateOfBirth] DATE NULL,
[city] NVARCHAR (50) NULL,
[address] NVARCHAR (50) NULL,
[phoneNumber] INT NULL,
[email] NVARCHAR (50) NULL,
[rank] NVARCHAR (50) NULL,
[profilImage] NVARCHAR (255) NULL,
PRIMARY KEY CLUSTERED ([userID] ASC),
CONSTRAINT [AK_User_username]
UNIQUE NONCLUSTERED ([username] ASC)
);
In my UserRelationship table, I store all relations by always making sure userFirstID is lower than userSecondID. So I only have 1 record per relation.

Do you want to get the names of the users the current user has a friendship with? Then one possibility is to join the user's table again twice for each the first and the second id in the relationship's table and check in a CASE ... END which one is the other user and return their name.
SELECT UserRelationship.relationshipType,
UserRelationship.userFirstID,
UserRelationship.userSecondID,
[User].username,
[User].firstName,
[User].lastName,
CASE [User].[UserID]
WHEN OtherUser1.userId
THEN OtherUser2.userName
WHEN OtherUser2.userId
THEN OtherUser1.userName
END OtherUserUserName,
CASE [User].[UserID]
WHEN OtherUser1.userId
THEN OtherUser2.firstName
WHEN OtherUser2.userId
THEN OtherUser1.firstName
END OtherUserFirstName,
CASE [User].[UserID]
WHEN OtherUser1.userId
THEN OtherUser2.lastName
WHEN OtherUser2.userId
THEN OtherUser1.lastName
END OtherUserLastName
FROM [User]
INNER JOIN UserRelationship
ON [User].userID IN (UserRelationship.userFirstID,
UserRelationship.userSecondID)
AND UserRelationship.relationshipType = 'friends'
INNER JOIN [User] OtherUser1
ON OtherUser1.userID = UserRelationship.userFirstID
INNER JOIN [User] OtherUser2
ON OtherUser2.userID = UserRelationship.userSecondID
WHERE ([User].userID = #userID);
(Assuming a user cannot be a friend of themselves. That would require an extension of the CASE .... ENDs for the case of all three ids being equal.)

Related

How to save auto generated primary key Id in foreign key column in same table

Following is the table structure:
CREATE TABLE [User] (
[Id] bigint identity(1,1) not null,
[FirstName] nvarchar(100) not null,
[LastName] nvarchar(100) not null,
[Title] nvarchar(5) null,
[UserName] nvarchar(100) not null,
[Password] nvarchar(100) not null,
[Inactive] bit null,
[Created] Datetime not null,
[Creator] bigint not null,
[Modified] DateTime null,
[Modifier] bigint null
CONSTRAINT [PK_User] PRIMARY KEY CLUSTERED
(
[Id] Asc
)
);
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[FK_User_Creator]') AND parent_object_id = OBJECT_ID(N'[User]'))
ALTER TABLE [User] ADD CONSTRAINT [FK_User_Creator] FOREIGN KEY([Creator]) REFERENCES [User]([Id])
GO
INSERT INTO [User] (Creator) Values ([Id] ?)
This is a case when table is empty and first user is going to add in table. Otherwise I don't have issue.
How can I insert Id in creator column with insert statement at the same time?
One way could be using Sequence instead of identity column. The below script might serve the same purpose:
CREATE SEQUENCE dbo.useridsequence
AS int
START WITH 1
INCREMENT BY 1 ;
GO
CREATE TABLE [User] (
[Id] bigint DEFAULT (NEXT VALUE FOR dbo.useridsequence) ,
[FirstName] nvarchar(100) not null,
[LastName] nvarchar(100) not null,
[Title] nvarchar(5) null,
[UserName] nvarchar(100) not null,
[Password] nvarchar(100) not null,
[Inactive] bit null,
[Created] Datetime not null,
[Creator] bigint DEFAULT NEXT VALUE FOR dbo.useridsequence ,
[Modified] DateTime null,
[Modifier] bigint null
CONSTRAINT [PK_User] PRIMARY KEY CLUSTERED
(
[Id] Asc
)
);
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[FK_User_Creator]') AND parent_object_id = OBJECT_ID(N'[User]'))
ALTER TABLE [User] ADD CONSTRAINT [FK_User_Creator] FOREIGN KEY([Creator]) REFERENCES [User]([Id])
GO
INSERT INTO [User]
(
-- Id -- this column value is auto-generated
FirstName,
LastName,
Title,
UserName,
[Password],
Inactive,
Created,
Creator,
Modified,
Modifier
)
VALUES
(
'Foo',
'Bar',
'Title',
'UserName ',
'Password',
0,
GETDATE(),
DEFAULT,
GETDATE(),
1
)
SELECT * FROM [User] AS u
Result :
The short answer is that you can't do this. And I suggest your model is logically flawed in the first place. Do you intend to define all actual database users (e.g., create user ... for login ...) as rows in [Users]? You need to think about that - but the typical answer is no. If the answer is yes, then you don't need the creator column at all because it is redundant. All you need is the created date - for which you probably should have defined a default.
But if you want to do this, you will need to do it in two steps (and you will need to make the column nullable). You insert a row (or rows) with values for the "real" data columns. Then update those same rows with the identity values generated for id. An example showing different ways to do this
use tempdb;
set nocount on;
CREATE TABLE dbo.[user] (
[user_id] smallint identity(3,10) not null primary key,
[name] nvarchar(20) not null,
[active] bit not null default (1),
[created] Datetime not null default (current_timestamp),
[creator] smallint null
);
ALTER TABLE dbo.[user] ADD CONSTRAINT [fk_user] FOREIGN KEY(creator) REFERENCES dbo.[user](user_id);
GO
-- add first row
insert dbo.[user] (name) values ('test');
update dbo.[user] set creator = SCOPE_IDENTITY() where user_id = SCOPE_IDENTITY()
-- add two more rows
declare #ids table (user_id smallint not null);
insert dbo.[user] (name) output inserted.user_id into #ids
values ('nerk'), ('pom');
update t1 set creator = t1.user_id
from #ids as newrows inner join dbo.[user] as t1 on newrows.user_id = t1.user_id;
select * from dbo.[user] order by user_id;
-- mess things up a bit
delete dbo.[user] where name = 'pom';
-- create an error, consume an identity value
insert dbo.[user](name) values (null);
-- add 2 morerows
delete #ids;
insert dbo.[user] (name) output inserted.user_id into #ids
values ('nerk'), ('pom');
update t1 set creator = t1.user_id
from #ids as newrows inner join dbo.[user] as t1 on newrows.user_id = t1.user_id;
select * from dbo.[user] order by user_id;
drop table dbo.[user];
And I changed the identity specification to demonstrate something few developers realize. It isn't always defined as (1,1) and the next inserted value can jump for many reasons - errors and caching/restarts for example. Lastly, I think you will regret naming a table with a reserved word since references to it will require the use of delimiters. Reduce the pain.

SQL Outer Join -- Join requires 3 tables

I'm using SQL Server query designer to try and form an outer query that will return the full name and address of each insured with home policies and those without policies. My create statements are the following:
CREATE TABLE Address (
AddressID integer NOT NULL,
HouseNumber Integer NOT NULL,
Street varchar(20) NOT NULL,
CityCounty varchar(20) NOT NULL,
StateAbb char(2),
CountryAbb char(2) NOT NULL,
Zip char(5) NOT NULL,
LastUpdatedBy varchar(20) NOT NULL,
LastUpdated date NOT NULL,
CONSTRAINT PK_Address PRIMARY KEY (AddressID));
CREATE TABLE Insured(
InsuredID integer NOT NULL,
FirstName varchar(15) NOT NULL,
LastName varchar(15) NOT NULL,
MI char(1),
DateOfBirth date NOT NULL,
CreditScore integer NOT NULL,
AddressID integer NOT NULL,
DriversLicenseNumber varchar(35),
LastUpdatedBy varchar(20) NOT NULL,
LastUpdated date NOT NULL,
CONSTRAINT PK_Insured PRIMARY KEY (InsuredID),
CONSTRAINT FK_InsuredAddress FOREIGN KEY (AddressID) references Address);
CREATE TABLE Policy(
PolicyID integer NOT NULL,
EffectiveDate date NOT NULL,
TerminationDate date NOT NULL,
Amount Numeric (8,2) NOT NULL,
PolicyYear integer NOT NULL,
PolicyType char(1) NOT NULL,
InsuredID integer NOT NULL,
AddressID integer NOT NULL,
LastUpdatedBy varchar(20) NOT NULL,
LastUpdated date NOT NULL,
CONSTRAINT PK_Policy PRIMARY KEY (PolicyID),
CONSTRAINT FK_PolicyAddress FOREIGN KEY (AddressID) references Address,
CONSTRAINT FK_PolicyInsured FOREIGN KEY (InsuredID) references Insured);
CREATE TABLE Home(
PolicyID integer NOT NULL,
ExteriorType varchar(30) NOT NULL,
Alarm char(3) NOT NULL,
DistanceToFireStation integer NOT NULL,
LastUpdatedBy varchar(20) NOT NULL,
LastUpdated date NOT NULL,
CONSTRAINT PK_Home PRIMARY KEY (PolicyID),
CONSTRAINT FK_HomePolicy FOREIGN KEY (PolicyID) references Policy);
CREATE TABLE Auto(
PolicyID integer NOT NULL,
VinNumber varchar(30) NOT NULL,
Make varchar(15) NOT NULL,
Model varchar(20) NOT NULL,
MilesPerYear integer NOT NULL,
LastUpdatedBy varchar(20) NOT NULL,
LastUpdated date NOT NULL,
CONSTRAINT PK_Auto PRIMARY KEY (PolicyID),
CONSTRAINT FK_AutoPolicy FOREIGN KEY (PolicyID) references Policy);
I believe that the query requires tables address, insured, policy and an outer right or left join but I cant get SQL server to recognize this as it keeps forming an inner join and cross join. What do I need for a query that returns insureds with home policies and their addresses and insureds with no policy and their addresses?
What I've tried so far:
SELECT Insured.InsuredID, Insured.FirstName,
Insured.LastName, Address.HouseNumber,
Policy.PolicyID
FROM Address RIGHT JOIN Policy
ON Address.AddressID = Policy.AddressID
RIGHT JOIN Insured ON Policy.AddressID = Insured.AddressID
ORDER BY Insured.InsuredID
This is the most recent query that returns what I need for insureds with a home policy but for the insureds without a policy I get nulls in the address.
SELECT i.InsuredID, i.FirstName, i.MI, i.LastName,
a.HouseNumber, a.Street, a.CityCounty, a.StateAbb, a.CountryAbb, a.Zip
FROM INSURED i
LEFT JOIN (SELECT * FROM Policy WHERE PolicyType = 'H') HomePolicy on
i.InsuredID = HomePolicy.InsuredID
LEFT JOIN Address a on HomePolicy.AddressID = a.AddressID;
Could you try this query:
SELECT i.InsuredID,
i.FirstName,
i.LastName,
a.HouseNumber,
p.PolicyID
FROM insured i
LEFT JOIN policy p ON i.AddressID = p.AddressID AND p.PolicyType = 'H'
LEFT JOIN address a ON i.AddressID = a.AddressID
ORDER BY i.InsuredID;
I think the joins were in the wrong order. Does this give you what you need?
Update: Joining the Insured table to the Address table will show you addresses regardless of if they have a policy or not.
Database design seem good.I think we have minor doubts regarding "PolicyType" column. what value it hold and what is the purpose of this column.
Say PolicyType='H' it mean that it is home policy . Or other way of finding same query is to check if that policyid exists in home table.
Is this correct ?
Main query,
What do I need for a query that returns insureds with home policies
and their addresses and insureds with no policy and their addresses?
Check this script,
--insureds with home policies and their addresses
select i.InsuredID,
i.FirstName,
i.LastName
A.HouseNumber
,1 INDICATE
from Insured i
INNER JOIN policy p ON i.InsuredID = p.InsuredID
INNER JOIN [Address] A ON A.ADDRESSID=I.ADDRESSID
WHERE EXISTS(SELECT PolicyID FROM Home H WHERE h.PolicyID=P.PolicyID)
AND NOT EXISTS(SELECT PolicyID FROM [Auto] a WHERE A.PolicyID=P.PolicyID)
UNION ALL
--insureds with no policy and their addresses
select i.InsuredID,
i.FirstName,
i.LastName
,A.HouseNumber
,0 INDICATE
from Insured i
INNER JOIN [Address] A ON A.ADDRESSID=I.ADDRESSID
WHERE EXISTS(SELECT InsuredID FROM policy p WHERE i.InsuredID = p.InsuredID )
I have use "EXISTS clause" because that table column is not require in your output.

I need to create a view in the database

I need to create a view in the database when two columns are refer from same table. I can create a view like this:
CREATE VIEW [dbo].[ViewJournal]
AS
SELECT
J. d, J.date, J.drac, L.name as draccount, J.crac,
L.name as craccount, J.dramt, J.cramt, J.lf,
J.description, J.voucherType, J.reg_date, J.last_update,
J.active
FROM
Journal J, Ledger L
WHERE
J.drac = L.Id
But the result doesn't not show actual result.
Here, crac and drac are refered to from Ledger table.
Journal table:
CREATE TABLE [dbo].[Journal]
(
[Id] DECIMAL (18) IDENTITY (1, 1) NOT NULL,
[date] DATETIME NULL,
[drac] DECIMAL (18) NULL,
[crac] DECIMAL (18) NULL,
[dramt] DECIMAL (18, 2) NULL,
[cramt] DECIMAL (18, 2) NULL,
[reg_date] DATETIME NULL,
[last_update] DATETIME NULL,
[active] INT NULL,
[lf] VARCHAR (50) NULL,
[description] NVARCHAR (150) NULL,
[voucherType] VARCHAR (50) NULL,
[sales] VARCHAR (50) NULL,
[purchase] VARCHAR (50) NULL,
[cash_paymentno] VARCHAR (50) NULL,
[cash_receiptno] VARCHAR (50) NULL,
[expense] VARCHAR (50) NULL,
[income] VARCHAR (50) NULL,
[advance] VARCHAR (50) NULL,
[remunaration] VARCHAR (50) NULL,
CONSTRAINT [PK_Journal] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_Ledger] FOREIGN KEY ([drac]) REFERENCES [dbo].[Ledger] ([Id]) ON DELETE CASCADE ON UPDATE CASCADE
);
Ledger table:
CREATE TABLE [dbo].[Ledger]
(
[Id] DECIMAL (18) IDENTITY (1, 1) NOT NULL,
[name] NVARCHAR (50) NULL,
[type] NVARCHAR (50) NULL,
[classification] VARCHAR (50) NULL,
[realornominal] VARCHAR (50) NULL,
[reg_date] DATETIME NULL,
[last_update] DATETIME NULL,
[active] DECIMAL (2) NULL,
[depree] VARCHAR (50) NULL,
CONSTRAINT [PK_Ledger] PRIMARY KEY CLUSTERED ([Id] ASC)
);
In your current query, you're joining on J.drac = L.Id, which means that L will always be the record which is referenced in J.drac, regardless of the value of J.crac.
The way I understand it, you want to reference two different records in the Ledger table. You need two joins for that.
SELECT
J.Id, J.date, J.drac, D.name as draccount, J.crac,
C.name as craccount, J.dramt, J.cramt, J.lf,
J.description, J.voucherType, J.reg_date, J.last_update,
J.active
FROM Journal J
INNER JOIN Ledger D ON J.drac = D.Id
INNER JOIN Ledger C ON J.crac = C.Id

Retrieve data using select query with null Foreign key value

I have a 2 tables with name Vendor and VendorType . Structure are given
CREATE TABLE XCodesSCMERP.dbo.Vendor (
VendorID INT IDENTITY,
VendorTypeID INT NULL,
VendorName VARCHAR(200) NULL,
VendorCompany VARCHAR(200) NULL,
FirstName VARCHAR(100) NULL,
LastName VARCHAR(100) NULL,
Contact VARCHAR(100) NULL,
Phone VARCHAR(100) NULL,
AltContact VARCHAR(100) NULL,
Email VARCHAR(50) NULL,
AddressBilledFrom VARCHAR(50) NULL,
AddressShippedFrom VARCHAR(50) NULL,
VendorNotes VARCHAR(500) NULL,
OpeningBalance VARCHAR(100) NULL,
OpeningDate VARCHAR(100) NULL,
VendorAccountNo VARCHAR(100) NULL,
CONSTRAINT PK_Vendor PRIMARY KEY CLUSTERED (VendorID),
CONSTRAINT FK_Vendor_VendorTypeTable_VendorTypeID FOREIGN KEY (VendorTypeID) REFERENCES dbo.VendorTypeTable (VendorTypeID)
) ON [PRIMARY]
GO
CREATE TABLE XCodesSCMERP.dbo.VendorTypeTable (
VendorTypeID INT IDENTITY,
VendorType VARCHAR(100) NULL,
VendorDesc VARCHAR(MAX) NULL,
CONSTRAINT PK_VendorTypeTable PRIMARY KEY CLUSTERED (VendorTypeID)
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
It is clear from structures of table that VendorTypeID is foreign key in Vendor table. Now when i want to retrieve data from Vendor table including field VendorType from VendorTypeTable than i have to use Inner Join that works fine.
But here is problem . it does' not show that records which don't have any vendorType i.e VendorTypeID is not selected . It is said to be null.
Now here is my question , how i can retrieve those records also that don't have any Vendor Type.
Would be pleasure for me , helping me in my Problem.
Note:
SELECT VendorID,VendorName,FirstName,LastName,VendorCompany,Contact,Phone,AltContact,Email,OpeningBalance,OpeningDate,VendorAccountNo ,VendorNotes FROM Vendor WHERE VendorTypeID='';
This query does not return any record.
If I understand correctly, you just want IS NULL:
SELECT v.*
FROM Vendor v
WHERE VendorTypeID IS NULL;
Modify your query to something like this
SELECT
VendorID,VendorName,FirstName,LastName,VendorCompany,Contact,Phone,AltContact,Email,OpeningBalance,OpeningDate,VendorAccountNo
,VendorNotes FROM Vendor WHERE VendorTypeID IS NULL;
Note: A NULL value is different from a zero value or a field that contains spaces. A field with a NULL value is a blank field

Retrieve Data from Different Tables (SQL Server)

I have 4 tables in a SQL Server database with following schema:
Attendance
CREATE TABLE [dbo].[Attendance] (
[AttendanceId] UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL,
[CourseId] UNIQUEIDENTIFIER NOT NULL,
[StudentId] UNIQUEIDENTIFIER NOT NULL,
[SubjectId] UNIQUEIDENTIFIER NOT NULL,
[Semester] INT NOT NULL,
[Month] NVARCHAR (50) NOT NULL,
[Count] INT NOT NULL,
CONSTRAINT [PK_Attendance] PRIMARY KEY NONCLUSTERED ([AttendanceId] ASC),
CONSTRAINT [FK_Attendance_Student] FOREIGN KEY ([StudentId]) REFERENCES [dbo].[Student] ([StudentId]) );
Course
CREATE TABLE [dbo].[Course] (
[CourseId] UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL,
[Name] NVARCHAR (50) NOT NULL,
CONSTRAINT [PK_Course] PRIMARY KEY NONCLUSTERED ([CourseId] ASC)
);
Student
CREATE TABLE [dbo].[Student] (
[StudentId] UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL,
[CourseId] UNIQUEIDENTIFIER NOT NULL,
[Name] NVARCHAR (100) NOT NULL,
[RollNo] INT NOT NULL,
[Semester] INT NOT NULL,
CONSTRAINT [PK_Student] PRIMARY KEY NONCLUSTERED ([StudentId] ASC),
CONSTRAINT [FK_Student_Course] FOREIGN KEY ([CourseId]) REFERENCES [dbo].[Course] ([CourseId])
);
Subject
CREATE TABLE [dbo].[Subject] (
[SubjectId] UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL,
[CourseId] UNIQUEIDENTIFIER NOT NULL,
[Name] NVARCHAR (100) NOT NULL,
[Semester] INT NOT NULL,
CONSTRAINT [PK_Subject] PRIMARY KEY NONCLUSTERED ([SubjectId] ASC),
CONSTRAINT [FK_Subject_Course] FOREIGN KEY ([CourseId]) REFERENCES [dbo].[Course] ([CourseId])
);
I need to create a attendance report in the following format:
Course Name | Student Name | Subject Name | Semester | Month | Count
Please tell me what SQL Query I need to use and if there's any change in schema required then suggest the same.
I'm looking forward to have your replies.
Thanks,
You need to use a JOIN in your query so that it only returns rows which match a [StudentId] from the Attendance table.
e.g.
SELECT c.CourseName, s.StudentName, u.SubjectName, u.Semester, a.Month, a.Count
FROM Student s
JOIN Attendance a ON s.StudentId = a.StudentId
JOIN Course c ON a.CourseId = c.CourseId
JOIN Subject u ON c.CourseId = u.CourseId
Something along these lines will only return rows which specifically match