CHECK CONSTRAINT ERROR USING SQL MANAGEMENT STUDIO - sql

CREATE TABLE [dbo].[SALES]
(
[SaleID] [uniqueidentifier] NOT NULL DEFAULT NEWID(),
[ProductID] [int] NOT NULL,
[WorkID] [int] NOT NULL,
[Quantity] [smallint] NOT NULL,
[SaleDate] [datetime] NOT NULL CONSTRAINT DF_SaleDate DEFAULT (GETDATE())
CONSTRAINT CHK_QuantitySaleDate CHECK (Quantity > 0 AND DATEDIFF (d,GETDATE(), SaleDate) <=0)
) ON [PRIMARY]
Trying to execute the above query results in the following error:
"Column CHECK constraint for column 'SaleDate' references another column, table 'SALES'."
Can someone please enlighten me?

It's because you are setting constraint as COLUMN constraint. You have to set it as TABLE constraint. So, after:
[SaleDate] [datetime] NOT NULL CONSTRAINT DF_SaleDate DEFAULT (GETDATE())
you need a comma sign, so it should be:
[SaleDate] [datetime] NOT NULL CONSTRAINT DF_SaleDate DEFAULT (GETDATE()),
CONSTRAINT...

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
)

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 Azure unique nonclustered constraint

Does SQL Azure support unique non-clustered constraints? Something like that:
CREATE TABLE [dbo].[MyTable] (
[Id] [int] IDENTITY(1,1) NOT NULL,
[FieldA] [nvarchar](50) NULL,
[FieldB] [nvarchar](50) NULL,
[FieldC] [int] NULL,
CONSTRAINT [PK_Id] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [UQ_ABC] UNIQUE NONCLUSTERED ([FieldA], [FieldB], [FieldC])
It is supported, between ending ) is missing in the above statement if that is troubling you

How can you define a computed column like this?

I have an Equipment table in SQL Server 2008 like this:
CREATE TABLE [dbo].[Equipment](
[EquipmentID] [nchar](10) NOT NULL,
[EquipmentName] [nchar](50) NOT NULL,
[ProducedDate] [date] NOT NULL,
[WarrantyPeriod] [int] NOT NULL,
[SerialNumber] [nchar](20) NOT NULL,
[BrandID] [tinyint] NOT NULL,
CONSTRAINT [PK_Equipment] PRIMARY KEY CLUSTERED
)
I want to have a computed column WarrantyStatus that will return either Unexpired or Expired when calculating, based on columns ProducedDate and WarrantyPeriod.
This is wrong, but it's what I want:
ALTER TABLE [dbo].[Equipment]
ADD [WarrantyStatus] AS IIF(DATEDIFF(MONTH, [ProducedDate], GETDATE()) < [WarrantyPeriod], "Unexpired", "Expired")
Try:
ALTER TABLE [dbo].[Equipment]
ADD [WarrantyStatus] AS
case when DATEDIFF(MONTH, [ProducedDate], GETDATE()) < [WarrantyPeriod]
then 'Unexpired'
else 'Expired'
end

Can't update column values, it is associated with a clustered index?

I am having some problems when trying to update column values, this column has a clustered index associated to it.
This is the update statement.
UPDATE dbo.VentureXRef
SET RefValue = REPLICATE('0',7 - LEN(RefValue)) + RefValue WHERE LEN(RefValue) < 7
This is the error I get
Cannot insert duplicate key row in
object 'dbo.VentureXRef' with unique
index 'idx_WFHMJVXRef_RefValueByType'.
This is mytable definition
CREATE TABLE [dbo].[VentureXRef]
(
[ID] [int] NOT NULL IDENTITY(1, 1),
[RefValue] [varchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[RefValueTypeID] [int] NOT NULL,
[State] [char] (2) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL CONSTRAINT [DF__WFHMJoint__State__2AC11801] DEFAULT (' '),
[ClientID] [int] NOT NULL,
[DoingBusinessAs] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[Disabled] [bit] NOT NULL CONSTRAINT [DF_VentureXRef_Disabled] DEFAULT (0),
[Username] [varchar] (64) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL CONSTRAINT [DF_VentureXRef_Username] DEFAULT (user_name()),
[DateDeleted] [datetime] NULL,
[DateLastModified] [datetime] NOT NULL CONSTRAINT [DF_VentureXRef_DateLastModified] DEFAULT (getdate())
) ON [PRIMARY]
GO
CREATE CLUSTERED INDEX [idx_WFHMJVXRef_RefValue] ON [dbo].[VentureXRef] ([RefValue], [State]) WITH (FILLFACTOR=80) ON [PRIMARY]
GO
ALTER TABLE [dbo].[VentureXRef] ADD CONSTRAINT [PK__WFHMJointVenture__28D8CF8F] PRIMARY KEY NONCLUSTERED ([ID]) WITH (FILLFACTOR=80) ON [PRIMARY]
GO
CREATE UNIQUE NONCLUSTERED INDEX [idx_WFHMJVXRef_RefValueByType] ON [dbo].[VentureXRef] ([RefValue], [State], [DateDeleted], [RefValueTypeID]) WITH (FILLFACTOR=80) ON [PRIMARY]
GO
ALTER TABLE [dbo].[VentureXRef] ADD CONSTRAINT [IX_VentureXRef] UNIQUE NONCLUSTERED ([RefValue], [RefValueTypeID], [State], [DateDeleted]) WITH (FILLFACTOR=80) ON [PRIMARY]
GO
ALTER TABLE [dbo].[VentureXRef] ADD CONSTRAINT [fk_WFHMJVXRef_ClientID] FOREIGN KEY ([ClientID]) REFERENCES [dbo].[Client] ([ClientID])
GO
ALTER TABLE [dbo].[VentureXRef] ADD CONSTRAINT [fk_WFHMJVXRef_RefValueTypeID] FOREIGN KEY ([RefValueTypeID]) REFERENCES [dbo].[VentureRefValueType] ([RefValueTypeID])
GO
What is the proper way to do this update statement?
Thanks in advance
YOur problem is you are trying to update it to a value that already exists in the table and so the unique index says it can't.
as mentioned by HILGEm this is a duplicate records problem.To identify records causing duplication you can run below query after substituting your table and database name in place of CTE
use test;
with cte as (
select '123' refvalue union all select '567' union all
select '0000123' union all
select '123456')
select refvalue from cte as a
where
len(refvalue) <7 and
exists(
select 1 from cte as b where
len(refvalue)>=7 and
REPLICATE('0',7 - LEN(a.RefValue)) + a.RefValue =b.refvalue
)