SQL unique column based on other columns - sql

I have a SQL Server database table that I am trying to fix without having to resort to using the front end code to determine if the name of the institute is unique. I am setting up a Linq to SQL code base for all of the inserts.
here is the new table that I am trying to setup:
CREATE TABLE [dbo].[institution]
(
[institutionID] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
[typeID] [tinyint] NOT NULL REFERENCES [dbo].[institutiontype]([institutiontypeID]),
[name] [varchar](255) NOT NULL UNIQUE,
[cityID] [int] NULL REFERENCES [dbo].[city]([cityID]),
[stateID] [int] NULL REFERENCES [dbo].[stateprovince]([stateID]),
[countryID] [int] NULL REFERENCES [dbo].[country]([countryID]),
[createby] [int] NOT NULL REFERENCES [dbo].[ipamuser]([ipamuserID]),
[createdatetime] [datetime] NOT NULL DEFAULT (GETDATE()),
[modifyby] [int] NULL REFERENCES [dbo].[ipamuser]([ipamuserID]),
[modifydatetime] [datetime] NULL,
[dataversion] [int] NOT NULL DEFAULT (0)
)
The issue is, the institutionname needs to be unique ONLY when the cityID, stateID and the countryID are the same. Setting up the table with the institutename as unique will not satisfy the needs since there are times when the same name can exist in different, cities, states or countries.
How would I resolve this

You need to write a complex constraint in your table. Define a user-defined-function which returns true (1 in BIT) if your required condition is satisfied and false otherwise.
Put this constraint in the table schema with a CHECK constraint.
CREATE FUNCTION dbo.fnIsNameUnique (
#name [varchar](255),
#cityID int,
#stateID int,
#countryID int,
)
RETURNS tinyint
AS
BEGIN
DECLARE #Result tinyint
IF EXISTS(SELECT * FROM institution WHERE name = #name AND cityID = #cityID AND stateID = #stateID AND countryID = #countryID)
SET #Result= 0
ELSE
SET #Result= 1
RETURN #Result
END
CREATE TABLE [dbo].[institution]
(
[institutionID] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
[typeID] [tinyint] NOT NULL REFERENCES [dbo].[institutiontype]([institutiontypeID]),
[name] [varchar](255) NOT NULL UNIQUE,
[cityID] [int] NULL REFERENCES [dbo].[city]([cityID]),
[stateID] [int] NULL REFERENCES [dbo].[stateprovince]([stateID]),
[countryID] [int] NULL REFERENCES [dbo].[country]([countryID]),
[createby] [int] NOT NULL REFERENCES [dbo].[ipamuser]([ipamuserID]),
[createdatetime] [datetime] NOT NULL DEFAULT (GETDATE()),
[modifyby] [int] NULL REFERENCES [dbo].[ipamuser]([ipamuserID]),
[modifydatetime] [datetime] NULL,
[dataversion] [int] NOT NULL DEFAULT (0),
CONSTRAINT ckValidName CHECK (
dbo.fnIsNameUnique(name, cityID, stateID, countryID) = 1)
)
)

I don't know why you need anything so complex, just putting a UNIQUE constraint or index on ([name], CityID, StateID, CountryID) does what you say you need.

Related

Filtering results between two dates with rdlc report in asp.net mvc

I am using RDLC for reports loaded into ASP.NET MVC.
I tried to filter the results between two dates, but when I type the following query below I get the following error:
"the new command text returns data with schema different from the schema of the main query. Check your query's command text if this is not desired."
Can you help me on how to do it?
SELECT
SiparisKalems.SiparisKalemId,
SiparisKalems.Siparisid,
SiparisKalems.SiparisKalemTarih,
SiparisKalems.SiparisKalemAdet,
SiparisKalems.SiparisKalemFiyat,
SiparisKalems.SiparisKalemToplam,
SiparisKalems.Urunid,
Uruns.Urunid AS Expr1,
Uruns.UrunAdi,
Uruns.UrunFiyat,
Uruns.UrunGorsel,
Uruns.Kategoriid,
Uruns.Durum
FROM
SiparisKalems
INNER JOIN Uruns ON SiparisKalems.Urunid = Uruns.Urunid
WHERE
(
SiparisKalems.SiparisKalemTarih >= #Param1
AND
SiparisKalems.SiparisKalemTarih <= #Param2
)
ORDER BY
SiparisKalems.SiparisKalemTarih DESC
CREATE TABLE [dbo].[SiparisKalems](
[SiparisKalemId] [int] NOT NULL IDENTITY(1,1),
[Siparisid] [int] NOT NULL,
[SiparisKalemTarih] [datetime] NOT NULL,
[SiparisKalemAdet] [int] NOT NULL,
[SiparisKalemFiyat] [decimal](18, 2) NOT NULL,
[SiparisKalemToplam] [decimal](18, 2) NOT NULL,
[Urunid] [int] NOT NULL,
CONSTRAINT PK_dbo.SiparisKalems PRIMARY KEY CLUSTERED ( [SiparisKalemId] ),
CONSTRAINT FK_dbo.SiparisKalems_dbo.Siparislers_Siparisid ([Siparisid]) REFERENCES [dbo].[Siparislers] ([Siparisid]) ON DELETE CASCADE,
CONSTRAINT [FK_dbo.SiparisKalems_dbo.Uruns_Urunid] FOREIGN KEY([Urunid]) REFERENCES [dbo].[Uruns] ([Urunid]) ON DELETE CASCADE
)
CREATE TABLE [dbo].[Uruns](
[Urunid] [int] NOT NULL IDENTITY(1,1),
[UrunAdi] [varchar](30) NOT NULL,
[UrunFiyat] [decimal](18, 2) NOT NULL,
[UrunGorsel] [varchar](250) NOT NULL,
[Kategoriid] [int] NOT NULL,
[Durum] [bit] NOT NULL,
CONSTRAINT [PK_dbo.Uruns] PRIMARY KEY ( [Urunid] ),
CONSTRAINT [FK_dbo.Uruns_dbo.Kategoris_Kategoriid] FOREIGN KEY([Kategoriid]) REFERENCES [dbo].[Kategoris] ([Kategoriid]) ON DELETE CASCADE
)

Computed column is not allowed to be used in another computed-column -- how can I allow it

CREATE TABLE [dbo].[tbl_Marks](
[ID] [int] IDENTITY(1,1) NOT NULL,
[SID] [int] NOT NULL FOREIGN KEY REFERENCES tbl_Student(ID),
[Year] [char](1) NOT NULL,
[ExamType] [char](5) NOT NULL,
[S1] [int] null constraint s1_marks check (s1 >=0 and s1<=25),
[S2] [int] null constraint s2_marks check (s2 >=0 and s2<=25),
[S3] [int] null constraint s3_marks check (s3 >=0 and s3<=25),
[S4] [int] null constraint s4_marks check (s4 >=0 and s4<=25),
[S5] [int] null constraint s5_marks check (s5 >=0 and s5<=25),
[TotalMarks] AS (S1+S2+S3+S4+S5),
[Avg] AS ((S1+S2+S3+S4+S5)/5),
[Percentage] AS (((S1+S2+S3+S4+S5)/125.0)*100),
[Rank] [tinyint] NULL,
[Grade] [char](1) NULL,
[CreatedBy] [varchar](25) NULL,
[CreatedOn] [datetime] NULL,
[ModifiedBy] [varchar](25) NULL,
[ModifiedOn] [datetime] NULL,
[Remarks] [varchar](500) NULL
CONSTRAINT [PK_tbl_Marks] PRIMARY KEY CLUSTERED([ID] ASC)
);
I created the about table and I want to display the Grade based on the Percentage and I created the Function for that and I dropped the existing column name is "Grade" and I Re-added the column "Grade" using alter command
ALTER TABLE tbl_marks DROP COLUMN Grade
ALTER TABLE tbl_Marks ADD Grade AS dbo.fn_CalculateGrade(percentage)
While adding the "Grade" column I got this error is:
Msg 1759, Level 16, State 0, Line 47
Computed column 'Percentage' in table 'tbl_Marks' is not allowed to be used in another computed-column definition.
This is my function:
CREATE FUNCTION dbo.fn_CalculateGrade(#Percentage DECIMAL)
RETURNS VARCHAR(10)
AS
BEGIN
-- Declare the return variable here
DECLARE #Grade VARCHAR(10)
SET #Grade = (CASE WHEN ISNULL(#Percentage,0) BETWEEN 60.00 AND 70.99 THEN 'D'
WHEN ISNULL(#Percentage,0) BETWEEN 71.00 AND 80.99 THEN 'C'
WHEN ISNULL(#Percentage,0) BETWEEN 81.00 AND 90.99 THEN 'B'
WHEN ISNULL(#Percentage,0) BETWEEN 91.00 AND 100.00 THEN 'A' END)
RETURN #Grade
END
GO
AND I try to add with out function also that query is:
UPDATE tbl_Marks SET Grade= (CASE WHEN ISNULL(Percentage,0) BETWEEN 60.00 AND 70.99 THEN 'D'
WHEN ISNULL(Percentage,0) BETWEEN 71.00 AND 80.99 THEN 'C'
WHEN ISNULL(Percentage,0) BETWEEN 81.00 AND 90.99 THEN 'B'
WHEN ISNULL(Percentage,0) BETWEEN 91.00 AND 100.00 THEN 'A' END)
How can I achieve this with out an any error?

SQL Server: select records, not linked to another table

I have a table:
CREATE TABLE [dbo].[CollectionSite]
(
[SiteCode] [nvarchar](32) NOT NULL,
[AddressId] [int] NOT NULL,
[RemittanceId] [int] NULL,
// additional columns
)
and a linked table:
CREATE TABLE [dbo].[CollectionSiteAddress]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](255) NULL,
[Address1] [nvarchar](255) NULL,
[Address2] [nvarchar](255) NULL,
[City] [nvarchar](128) NULL,
[State] [nvarchar](64) NULL,
[Zip] [nvarchar](32) NULL,
)
Relationship between these 2 tables:
ALTER TABLE [dbo].[CollectionSite] WITH CHECK
ADD CONSTRAINT [FK_CollectionSite_CollectionSiteAddress_AddressId]
FOREIGN KEY([AddressId]) REFERENCES [dbo].[CollectionSiteAddress] ([Id])
GO
ALTER TABLE [dbo].[CollectionSite] WITH CHECK
ADD CONSTRAINT [FK_CollectionSite_CollectionSiteAddress_RemittanceId]
FOREIGN KEY([RemittanceId]) REFERENCES [dbo].[CollectionSiteAddress] ([Id])
GO
I want to select all records from CollectionSiteAddress, which are not linked to CollectionSite (neither AddressId nor RemittanceId). Which request should I use?
I tried:
SELECT *
FROM CollectionSiteAddress
LEFT JOIN CollectionSite ON CollectionSiteAddress.Id = CollectionSite.AddressId
OR CollectionSiteAddress.Id = CollectionSite.RemittanceId
but it selects all records from CollectionSiteAddress
You are missing this WHERE clause:
WHERE CollectionSite.[SiteCode] IS NULL
because you want all the unmatched rows of CollectionSiteAddress.
I used the column [SiteCode] to check if it is NULL because it is not nullable in the definition of the table.
So you can write your query like this (shortened with aliases):
SELECT csa.*
FROM CollectionSiteAddress csa LEFT JOIN CollectionSite cs
ON csa.Id = cs.AddressId OR csa.Id = cs.RemittanceId
WHERE cs.[SiteCode] IS NULL
Or use NOT EXISTS:
SELECT csa.*
FROM CollectionSiteAddress csa
WHERE NOT EXISTS (
SELECT 1
FROM CollectionSite cs
WHERE csa.Id = cs.AddressId OR csa.Id = cs.RemittanceId
)

How to assign 2 default values to SQL table column?

I am designing user registration table with below columns.
CREATE TABLE [dbo].[NCT_UserRegistration]
(
[User_Id] [int] IDENTITY(1,1) NOT NULL,
[User_EmailId] [varchar](255) NULL,
[User_Password] [varchar](512) NULL,
[User_Name] [varchar](255) NULL,
[User_MobileNum] [varchar](20) NULL,
[User_Status] [varchar](15) NULL,
[User_Role] [varchar](20) NULL,
[User_CreatedDate] [timestamp] NULL,
[User_UpdatedDate] [datetime] NULL,
[Name] [varchar](30) NULL
)
My requirement for the status and role as below.
status VARCHAR(15) Index, Enumeration of ENABLED, DISABLED.
role VARCHAR(20) Enumeration of SUPER_ADMIN and PROJECT_ADMIN
What I understood from above is status should take only Enabled or Disabled and same with role also. How can I design my table to make sure it takes only those two values? Also is there any way for example if I supply 1 then it is ENABLED and 0 for DISABLED.
May I get some ideas here? Any help would be appreciated. Thank you
You need to use CHECK CONSTRAINT to limit to specific values
CREATE TABLE [dbo].[NCT_UserRegistration](
[User_Id] [int] IDENTITY(1,1) NOT NULL,
[User_EmailId] [varchar](255) NULL,
[User_Password] [varchar](512) NULL,
[User_Name] [varchar](255) NULL,
[User_MobileNum] [varchar](20) NULL,
[User_Status] [varchar](15) NULL CONSTRAINT chk_Status CHECK ([User_Status] IN ('ENABLED', 'DISABLED')),
[User_Role] [varchar](20) NULL CONSTRAINT chk_Role CHECK ([User_Role] IN ('SUPER_ADMIN','DISABLED')),
[User_CreatedDate] [timestamp] NULL,
[User_UpdatedDate] [datetime] NULL,
[Name] [varchar](30) NULL
)
For enumeration you will have to handle at front end or while retriving values from table which is an extra step.
SELECT CASE WHEN [User_Status] = 1 THEN 'ENABLED' WHEN [User_Status] = 0 THEN 'DISABLED' END As UserStratus
FROM [dbo].[NCT_UserRegistration]
Can you try adding constraint as below for status field. If its working then apply the same to ROLE field.
alter table NCT_UserRegistration
add (STATUS VARCHAR(15) default 'ENABLED',
constraint conSTATUS check (STATUS in ('ENABLED', 'DISABLED')))
There are two possible approaches.
Check constraints - #mh2017 has explained this well in his answer.
Looking at the conversation that seems to fit your requirements better, but just for the sake of sharing idea, I will mention -
Foreign key constraint (FK)- If it is acceptable to modify the User_Status and User_Role columns to be of type tinyint (or similar number type), you can store just the ids in these and create enumeration (aka mapping tables) to store what the ids represent.
Create FK on User_Status and User_Role in NCT_UserRegistration to refer to the enumeration tables.
FKC ensures that the referring column (User_Status and User_Role in NCT_UserRegistration) cannot have value other than those listed in the referred to column (the respective id columns in the enumeration tables)
This Foreign key vs check constraint for integrity post also describes few benefits of using FK over check constraint
Here is a sample code showing foreign key approach
CREATE TABLE [dbo].[NCT_UserRegistration](
[User_Id] [int] IDENTITY(1,1) NOT NULL,
[User_EmailId] [varchar](255) NULL,
[User_Password] [varchar](512) NULL,
[User_Name] [varchar](255) NULL,
[User_MobileNum] [varchar](20) NULL,
[User_Status] tinyint NULL, -- I changed this from varchar to tinyint
[User_Role] tinyint NULL, -- I changed this from varchar to tinyint
[User_CreatedDate] [timestamp] NULL,
[User_UpdatedDate] [datetime] NULL,
[Name] [varchar](30) NULL
)
create table StatusEnumeration
(
StatusId tinyint,
Description varchar(10)
constraint pk_StatusEnumeration__StatusId primary key clustered (StatusId)
)
insert into StatusEnumeration(StatusId, Description)
values
(0, 'Disabled'),
(1, 'Enabled')
create table RoleEnumeration
(
RoleId tinyint,
Description varchar(20)
constraint pk_RoleEnumeration__RoleId primary key clustered (RoleId)
)
insert into RoleEnumeration(RoleId, Description)
values
(0, 'SUPER_ADMIN '),
(1, 'PROJECT_ADMIN')
alter table NCT_UserRegistration
add constraint fk_NCT_UserRegistration__StatusEnumeration_StatusId foreign key (User_Status)
references StatusEnumeration (StatusId)
go
alter table NCT_UserRegistration
add constraint fk_NCT_UserRegistration__RoleEnumeration_RoleId foreign key (User_Role)
references RoleEnumeration (RoleId)
go

SQL Check Constraint with User Defined Function

I am troubleshooting an issue seen in our sql server database recently.
Table 1 has a calculated bit column based off of a user defined function which checks if a record exists in another table and evaluates to 0 if not.
Table 2 is the table searched by the function for Table 1. Table 2 also has a check constraint using a function to see if the bit field in Table 1 is set to 1.
This seems like a circular dependency. The problem is that when inserting a batch of records into Table 2, the constraint fails. Inserting these same records 1 by 1 allows all of the inserts to go through. I can't for the life of me figure out why batch inserts cause it to fail. Any help is appreciated.
CREATE TABLE [dbo].[tPecosPriceCheckStoreSubcategory](
[PecosPriceCheckID] [int] NOT NULL,
[StoreID] [int] NOT NULL,
[SubcategoryID] [int] NOT NULL,
[UndirectedExpectedScans] [int] NULL,
[PriceMin] [decimal](8, 2) NULL,
[PriceMax] [decimal](8, 2) NULL,
[PastPriceVariancePercent] [decimal](5, 2) NULL,
[ChangeDate] [datetime] NOT NULL,
[IsUndirected] [bit] NOT NULL,
[IsDirected] AS ([dbo].[fnPecosPriceCheckStoreSubcategoryIsDirected]([PecosPriceCheckID],[SubcategoryID])),
CONSTRAINT [PK_tPecosPriceCheckStoreSubcategory] PRIMARY KEY CLUSTERED
(
[PecosPriceCheckID] ASC,
[StoreID] ASC,
[SubcategoryID] ASC
)
ALTER TABLE [dbo].[tPecosPriceCheckStoreSubcategory] ADD CONSTRAINT [DF_IsUndirected] DEFAULT ((0)) FOR [IsUndirected]
GO
CREATE FUNCTION [dbo].[fnPecosPriceCheckStoreSubcategoryIsDirected]
(
#PecosPriceCheckID int,
#SubcategoryID int
)
RETURNS bit
AS
BEGIN
declare #isDirected bit
set #isDirected = 0
if (exists (select 1 from tPecosDirectedPriceCheckItem where PecosPriceCheckID = #PecosPriceCheckID and SubcategoryID = #SubcategoryID ))
begin
set #isDirected = 1
end
return #isDirected
END
CREATE TABLE [dbo].[tPecosDirectedPriceCheckItem](
[ID] [int] IDENTITY(1,1) NOT NULL,
[PecosPriceCheckID] [int] NOT NULL,
[PecosItemID] [int] NOT NULL,
[ItemSortOrder] [int] NOT NULL,
[SubcategoryID] [int] NOT NULL,
[ChangeDate] [datetime] NULL,
CONSTRAINT [PK_tPecosDirectedPriceCheckItem] PRIMARY KEY CLUSTERED
(
[ID] ASC
)
ALTER TABLE [dbo].[tPecosDirectedPriceCheckItem] WITH NOCHECK ADD CONSTRAINT [CK_tPecosDirectedPriceCheckItem_CheckPriceCheckSubcategoryDirected] CHECK (([dbo].[fnCheckDirectedItemPriceCheckSubcategory]([PecosPriceCheckID],[SubcategoryID])=(0)))
GO
ALTER TABLE [dbo].[tPecosDirectedPriceCheckItem] CHECK CONSTRAINT [CK_tPecosDirectedPriceCheckItem_CheckPriceCheckSubcategoryDirected]
GO
CREATE FUNCTION [dbo].[fnCheckDirectedItemPriceCheckSubcategory]
(
#PriceCheckID INT,
#SubcategoryID INT
)
RETURNS BIT
AS
BEGIN
DECLARE #isViolation BIT
SET #isViolation =
CASE WHEN EXISTS (SELECT * FROM tPecosPriceCheckStoreSubcategory WHERE SubcategoryID = #SubcategoryID AND PecosPriceCheckID = #PriceCheckID AND IsDirected = 1)
THEN
0
ELSE
1
END
RETURN #isViolation
END