Making one of my columns default the DateCreated to current time - sql

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.

Related

System-versioned table and primary key in SQL Server

Can I create different SQL script for system version table creation and primary key in SQL Server? When I do it, its throwing an error
System version table must have primary key defined
For example:
CREATE TABLE test
(
[ID] int IDENTITY(1,1) NOT NULL,
[name] varchar (1024),
[SysStart] [datetime2] (7) GENERATED ALWAYS AS ROW START NOT NULL,
[SysEnd] [datetime2] (7) GENERATED ALWAYS AS ROW END NOT NULL,
PERIOD FOR SYSTEM_TIME ([SysStart], [SysEnd])
)
WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = TESTHISTORY, DATA_CONSISTENCY_CHECK = ON))
ALTER TABLE Test
ADD CONSTRAINT [PK_Test]
PRIMARY KEY CLUSTERED (ID) ASC
Specify the constraint in the CREATE TABLE statement, eg:
Create table test
(
[ID] int identity(1,1) not null,
Constraint [PK_Test] PRIMARY KEY CLUSTERED (ID),
[name] varchar (1024),
[SysStart] [datetime2] (7) GENERATED ALWAYS AS ROW START NOT NULL,
[SysEnd] [datetime2] (7) GENERATED ALWAYS AS ROW END NOT NULL,
PERIOD FOR SYSTEM_TIME ([SysStart], [SysEnd]),
)
WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.TESTHISTORY, DATA_CONSISTENCY_CHECK = ON))
You can.
use tempdb;
drop table if exists dbo.test;
drop table if exists dbo.TESTHISTORY;
CREATE TABLE dbo.Test
(
[ID] int IDENTITY(1,1) NOT NULL,
[name] varchar (1024),
[SysStart] [datetime2] (7) GENERATED ALWAYS AS ROW START NOT NULL,
[SysEnd] [datetime2] (7) GENERATED ALWAYS AS ROW END NOT NULL,
PERIOD FOR SYSTEM_TIME ([SysStart], [SysEnd])
)
ALTER TABLE dbo.Test
ADD CONSTRAINT [PK_Test]
PRIMARY KEY CLUSTERED (ID)
ALTER TABLE dbo.Test
SET (SYSTEM_VERSIONING = ON (
HISTORY_TABLE = dbo.TESTHISTORY,
DATA_CONSISTENCY_CHECK = ON
)
);
It is probably my limited imagination, but I can't for the life of me think of what you stand to gain by doing so. That is, what outcome does having the primary key be a separate statement enable that doing inline inhibits?

How can I add a column and populate it with a number after sorting a table?

I have this table:
CREATE TABLE [dbo].[Phrase]
(
[PhraseId] [uniqueidentifier] NOT NULL,
[PhraseNum] [int] NULL
[English] [nvarchar](250) NOT NULL,
PRIMARY KEY CLUSTERED ([PhraseId] ASC)
) ON [PRIMARY]
GO
What I would like to do is to sort the table and populate the column PhraseNum with a number where the first row of the sorted table is 1 and each row after that has a value one larger than the one before.
Alan, if data in PhraseNum is not important (as I could see in your post), you can drop that column and add as an identity column
ALTER TABLE Phrase drop column PhraseNum ;
ALTER TABLE Phrase Add PhraseNum int identity(1,1) not null;
The numbering of PhraseNum will be done by the cluster index sorting criteria, so by PhraseId
But it is safe to test on a test database first
In SQL Server, you would do this with an identity column:
CREATE TABLE [dbo].[Phrase](
[PhraseId] [uniqueidentifier] NOT NULL PRIMARY KEY,
[PhraseNum] int identity(1, 1) NOT NULL
[English] [nvarchar](250) NOT NULL
);
Having a unique identify as a (clustered) primary key is a really, really bad idea. Why? New values are not ordered. That means that the data has to be re-ordered for each insert -- causing fragmentation.
You should use the PhraseNum column as the primary key.

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

Add nullable datetime column to Primary Key

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.

MS Access Create Table with Autoincrement and default date

I try to create MS Access Table with autoincrement ID and Default Date field, but next query always says "Syntax error in CREATE TABLE statement.":
CREATE TABLE Table1
(
[ID] AUTOINCREMENT,
[Email] TEXT(255),
[ProductID] NUMBER,
[DateCreate] DATETIME,
[DateSend] DATETIME
);
ALTER TABLE Table1
ALTER [DateSend] DATETIME DEFAULT NOW() NOT NULL;
Who can help me to fix that query. Thanks!
There are many NUMBER types in Ms-Access, so you have to be specific. I guess you want Integer.
CREATE TABLE Table1
(
[ID] AUTOINCREMENT,
[Email] TEXT(255),
[ProductID] INTEGER,
[DateCreate] DATETIME,
[DateSend] DATETIME
);
The ALTER TABLE syntax requires ALTER COLUMN :
ALTER TABLE Table1
ALTER COLUMN
[DateSend] DATETIME DEFAULT NOW() NOT NULL;
You could also have those two in one statement:
CREATE TABLE Table1
(
[ID] AUTOINCREMENT,
[Email] TEXT(255),
[ProductID] INTEGER,
[DateCreate] DATETIME,
[DateSend] DATETIME DEFAULT NOW() NOT NULL
);
It's best practise to have a PRIMARY KEY on every table, and you probably intended that for the ID:
[ID] AUTOINCREMENT PRIMARY KEY,
A page with a lot of useful information about how to handle Access with SQL:
Intermediate Microsoft Jet SQL for Access 2000
CREATE TABLE Tblcontact
(
contactid AUTOINCREMENT PRIMARY KEY ,
firstname CHAR (60),
lastname CHAR (60),
email VARCHAR (75)
);