How can you define a computed column like this? - sql

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

Related

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

CHECK CONSTRAINT ERROR USING SQL MANAGEMENT STUDIO

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...

Output data from current month?

I have this table and i want to ge the data from current month.
This is the table:
CREATE TABLE [dbo].[CSEReduxResponses](
[response_id] [int] IDENTITY(1,1) NOT NULL,
[submitterdept] [int] NOT NULL,
[commentdate] [datetime] NOT NULL,
[status] [int] NOT NULL,
[approvedby] [int] NULL,
[approveddate] [datetime] NULL,
[execoffice_approvedby] [int] NULL,
CONSTRAINT [PK_CSE_Responses] PRIMARY KEY CLUSTERED
(
I want to get the data where
status=1 and execoffice_status=0 and the current date.I want to use the approveddata column to get the date.
Right now I have
select * from CSEReduxResponses WHERE STATUS=1 AND EXECOFFICE_STATUS=0;
I have Microsoft sql server 2008
Microsoft SQL Server Management Studio 10.0.2531.0
Add AND MONTH([approveddate]) = MONTH(GETDATE()) AND YEAR([approveddate]) = YEAR(GETDATE()) to your where clause, assuming [approveddate] is the date you're interested in.
It is simple:
SELECT *
FROM CSEReduxResponses
WHERE STATUS = 1
AND EXECOFFICE_STATUS = 0;
AND MONTH(commentdate) = MONTH(GETDATE())
AND YEAR(commentdate) = YEAR(GETDATE())

How to create a trigger to modify date column on table with double key

I need to create a trigger that saves the current date&timestamp into the row when it is being inserted or updated.
Table structure
[Period] [char](7) NOT NULL,
[CompanyAlfaCode] [char](2) NOT NULL,
[SamplePercentaje] [int] NULL,
[Usuario] [varchar](50) NULL,
[Date] [Datetime] NULL,
Thank you very much.
Maybe something like:
CREATE TRIGGER DateTrigger ON CompanySampleConfig
AFTER INSERT,UPDATE
AS
BEGIN
UPDATE CompanySampleConfig SET [Date] = current_timestamp
WHERE EXISTS
(SELECT '' FROM inserted
WHERE CompanySampleConfig.[Period] = inserted.[Period]
AND CompanySampleConfig.[CompanyAlfaCode] = inserted.[CompanyAlfaCode]
END