Add nullable datetime column to Primary Key - sql

I have a table with following columns:
[ClauseID] [int] NOT NULL,
[PolicyCategoryID] [int] NOT NULL,
[ExpiryDate] [smalldatetime] NULL,
By now ClauseID and PolicyCategoryID together creates the primary key. But I want ExpiryDate also be a part of primary key. To make the column not null I tried the following but it gives an error:
ALTER TABLE tblClauses_PolicyCategory
ALTER COLUMN [ExpiryDate] SMALLDATETIME NOT NULL DEFAULT '2079-06-06'
Incorrect syntax near the keyword 'DEFAULT'.
Any idea why? Is it not possible to set a default date like this?
EDIT: By bad! Default key was already set. That must be the reason it gave an error.

try this:
ALTER TABLE tblClauses_PolicyCategory
ALTER COLUMN [ExpiryDate] SMALLDATETIME NOT NULL
ALTER TABLE tblClauses_PolicyCategory ADD CONSTRAINT
cons_expiryDate DEFAULT '2079-06-06' FOR ExpiryDate
Before execute these lines, please check if exists some rows with ExpiryDate null, if yes, please, update all nullable rows to default value

I think this will help you:
CREATE TABLE tblClauses_PolicyCategory(
[ClauseID] [int] NOT NULL,
[PolicyCategoryID] [int] NOT NULL,
[ExpiryDate] [smalldatetime] NULL)
ALTER TABLE tblClauses_PolicyCategory
ALTER COLUMN [ExpiryDate] SMALLDATETIME NOT NULL
ALTER TABLE tblClauses_PolicyCategory
ADD CONSTRAINT cons_default DEFAULT '2079-06-06' FOR ExpiryDate
But, before changing ExpireDate to NOT NULL, you must populate values for existing rows in this column, and then change column to NOT NULL.

Related

Cannot insert the value NULL into column 'Id' although Id is set

I have a strange problem.
I want to insert an item to a table from database. I use Entity Framework.
Although the Id is set, I keep getting the following error:
Cannot insert the value NULL into column 'Id', table 'project_atp.dbo.ShoppingCarts'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated."}
The table definition:
CREATE TABLE [dbo].[ShoppingCarts] (
[Id] INT NOT NULL,
[Guid] UNIQUEIDENTIFIER NULL,
[Name] NVARCHAR (255) NULL,
[Code] NVARCHAR (255) NULL,
[SupplierNo] NVARCHAR (255) NULL,
[SupplierName] NVARCHAR (255) NULL,
[Price] NVARCHAR (50) NULL,
[Quantity] INT NULL,
CONSTRAINT [PK_ShoppingCarts] PRIMARY KEY CLUSTERED ([Id] ASC)
);
Can you please advise what could be wrong here! Thanks!
By default Entity Framework assumes that an integer primary key is database generated. As the result Entity Framework would not include Primary Key field in the actual INSERT statement.
I would try to either play along and ALTER the table to auto-generate the ID (which judging by your comment you did)
or set StoreGeneratedPattern property of OnlineCarStore.Models.ShoppingCarts Id column to 'None'
or use annotation: [DatabaseGenerated(DatabaseGeneratedOption.None)].

Alter column properties in SQL [duplicate]

This question already has answers here:
Default getdate for Insert date
(9 answers)
Closed 8 years ago.
I am trying to make a change to the data type for a column in an existing table. This column currently is empty but the table has dependencies which makes it impractical to drop and recreate the table.
The table currently looks like:
CREATE TABLE [dbo].[van_Payment](
[PaymentUID] [int] IDENTITY(1,1) NOT NULL,
[SponsorshipUID] [int] NOT NULL,
[PaymentMethodUID] [int] NOT NULL,
[Amount] [int] NOT NULL,
[Created] [int] NOT NULL,
GO
I need to change the following:
ALTER TABLE [dbo].[van_Payment]
ALTER COLUMN [Created] [smalldatetime] NOT NULL DEFAULT GETDATE(),
GO
I am getting the following error:
Msg 156, Level 15, State 1, Line 2 Incorrect syntax near the keyword
'DEFAULT'.
Any help with the correct syntax would be appreciated.
I don't think it possible to add default constraint using alter column syntax. Try this.
ALTER TABLE [dbo].[van_Payment]
ALTER COLUMN [Created] [smalldatetime] NOT NULL
GO
ALTER TABLE dbo.[van_Payment] ADD CONSTRAINT DF_Created DEFAULT getdate() FOR [Created];

Making one of my columns default the DateCreated to current time

I have the following SQL definition:
CREATE TABLE [dbo].[James] (
[JamesID] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (255) NOT NULL,
[DateCreated] DATETIME NULL,
CONSTRAINT [PK_dbo.James] PRIMARY KEY CLUSTERED ([JamesID] ASC)
);
How might I make it so new entries have the DateCreated filled out automatically when I create new entries.
What about existing data that has not had that column filled out?
If you are starting from scratch and assuming this is SQL Server:
CREATE TABLE [dbo].[James] (
[JamesID] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (255) NOT NULL,
[DateCreated] DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT [PK_dbo.James] PRIMARY KEY CLUSTERED ([JamesID] ASC)
);
If you want to update the table you can use this:
ALTER TABLE dbo.James
ADD CONSTRAINT DF_namehere DEFAULT CURRENT_TIMESTAMP FOR DateCreated;
However, any current NULL values will remain NULL with the ALTER TABLE solution. How you want to address this depends if you want to backfill information.

How do I alter table to add defaults?

I'd like to modify a table that already has data in the database to have a column reflect default data when it is populated.
Specifically, I'd like to take two columns:
[Created] [datetime] NULL ,
[CreatedBy] [varchar](50) NULL ,
And change them to have defaults like the following:
[Created] [datetime] NULL DEFAULT GETDATE(),
[CreatedBy] [varchar](50) NULL DEFAULT USER_ID(),
Can something like this be accomplished with an alter table statement? I'm using Azure so I can't edit the tables in the GUI.
ALTER TABLE dbo.TableName
ADD CONSTRAINT df_Created DEFAULT (GETDATE()) FOR Created;
ALTER TABLE dbo.TableName
ADD CONSTRAINT df_CreatedBy DEFAULT (USER_ID()) FOR CreatedBy;
Check the documentation for ALTER TABLE...

How to add multiple columns to a table and add default constraint on one of them?

I want to add 2 new columns to existing table.
One of them should be NOT NULL with default value 0
(filled in the existing rows as well).
I have tried the following syntax:
Alter TABLE dbo.MamConfiguration
add [IsLimitedByNumOfUsers] [bit] NOT NULL,
CONSTRAINT IsLimitedByNumOfUsers_Defualt [IsLimitedByNumOfUsers] DEFAULT 0
[NumOfUsersLimit] [int] NULL
go
But it throws exception. How should I write it?
You can use this:
ALTER TABLE dbo.MamConfiguration
ADD [IsLimitedByNumOfUsers] [BIT] NOT NULL DEFAULT 0,
[NumOfUsersLimit] [INT] NULL
GO
or this:
ALTER TABLE dbo.MamConfiguration
ADD [IsLimitedByNumOfUsers] [BIT] NOT NULL
CONSTRAINT IsLimitedByNumOfUsers_Default DEFAULT 0,
[NumOfUsersLimit] [INT] NULL
go
More: ALTER TABLE
Try this.
ALTER TABLE dbo.MamConfiguration
ADD [IsLimitedByNumOfUsers] [bit] NOT NULL DEFAULT 0,
[NumOfUsersLimit] [int] NULL
To add multiple columns to a table and add default constraint on one of them-
ALTER TABLE dbo.MamConfiguration
ADD [IsLimitedByNumOfUsers] [BIT] CONSTRAINT Def_IsLimitedByNumOfUsers DEFAULT(0) NOT NULL,
[NumOfUsersLimit] [INT] NULL;
GO
Each column is different;
ALTER TABLE
MamConfiguration
ADD
Configuration1 BIT NULL, --this column is nullable
Configuration2 BIT NOT NULL, --this column is not nullable
Configuration3 BIT NOT NULL DEFAULT(0), --this column is not nullable and set default value is 0(zero)
Configuration4 BIT NOT NULL CONSTRAINT DF_Configuration4 DEFAULT(0) --this column is not nullable and set default value is 0(zero) with spesific constraint name
GO